如何为此编写CUDA全局函数?

San*_*eep 1 cuda

我想将以下函数转换为CUDA。

void fun()
{
    for(i = 0; i < terrainGridLength; i++)
    {
       for(j = 0; j < terrainGridWidth; j++) 
       {
             //CODE of function
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

我写了这样的功能:

__global__ void fun()
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    int j = blockIdx.y * blockDim.y + threadIdx.y;

    if((i < terrainGridLength)&&(j<terrainGridWidth))
    {
           //CODE of function
    }
}
Run Code Online (Sandbox Code Playgroud)

我将terrainGridLength和terrainGridGridWidth都声明为常量,并为它们都分配了值120。我正在调用像

有趣的<<< 30,500 >>>()

但是我没有得到正确的输出。

我写的代码是正确的吗。我对代码的并行执行了解得不多。请向我解释代码将如何工作,如果我犯了任何错误,请更正我。

ard*_*u07 5

使用y维表示您正在使用2D数组线程,因此不能仅使用以下命令调用内核:

int numBlock = 30;
int numThreadsPerBlock = 500;
fun<<<numBlock,numThreadsPerBlock>>>()
Run Code Online (Sandbox Code Playgroud)

调用应为:(请注意,现在,块具有2D线程)

dim3 dimGrid(GRID_SIZE, GRID_SIZE); // 2D Grids with size = GRID_SIZE*GRID_SIZE
dim3 dimBlocks(BLOCK_SIZE, BLOCK_SIZE); //2D Blocks with size = BLOCK_SIZE*BLOCK_SIZE  
fun<<<dimGrid, dimBlocks>>>()
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅《CUDA编程指南》,此外,如果要执行2D数组或3D,则最好使用cudaMalloc3D或cudaMallocPitch

在您的代码中,我认为这可以工作(但是我还没有尝试过,希望您可以从中获得灵感):

//main
dim3 dimGrid(1, 1); // 2D Grids with size = 1
dim3 dimBlocks(Width, Height); //2D Blocks with size = Height*Width 
fun<<<dimGrid, dimBlocks>>>(Width, Height)

//kernel
__global__ void fun(int Width, int Height)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    int j = blockIdx.y * blockDim.y + threadIdx.y;

    if((i < Width)&&(j<Height))
    {
           //CODE of function
    }
}
Run Code Online (Sandbox Code Playgroud)