嵌套循环 Cuda C

Nested Loop Cuda C

我有一个一维整数数组,我想并行化 2 个 for 循环。

void foo(int *array, int width, int height) {
    for (i = 0 ; i < height ; i++) {
        for (j = 0 ; j < width ; j++) {
            /* do smth */
        }
    }
}

这是 "convert" 到 Cuda 的正确方法吗?

__global__ void foo(int *array, int width, int height) {
    unsigned int i = blockIdx.y*blockDim.y + threadIdx.y;
    unsigned int j = blockIdx.x*blockDim.x + threadIdx.x;
    if (i < height && j < width) {
        /* do smth */
    }
} 

还有,我应该如何从 main 调用内核 foo?

是的,这是让每个线程执行该循环迭代的正确方法。

为了调用内核 foo,您将需要指定 GridBlock 维度和 allocate/initialize 设备的内存。它看起来像这样。

int main(){
    /* Width/Height initialization up to you */
    int width, height;

    /* Device-Level Allocations, etc */
    int *h_arr, *d_arr;
    size_t array_size = width * height * sizeof(int);

    /* Allocate and Initialize Device-level memory */
    cudaMalloc((void **) &d_arr, array_size);
    cudaMemcpy(d_arr, h_arr, array_size, cudaMemcpyHostToDevice);

    /* Specify layout of Grid and Blocks */
    dim3 threads_per_block(width, height);
    dim3 blocks_per_dimension(block_x_dim, block_y_dim);

    /* Kernel Invocation */
    foo<<<blocks_per_dimension, threads_per_block>>>(d_arr, width, height);
}

NVidia 网站上有一些很好的资源,可以帮助您了解更多有关 CUDA 平台的信息。我强烈建议通读其中的一些内容——它可以帮助您入门。

Intro to CUDA C