【问题标题】:Nested Loop Cuda C嵌套循环 Cuda C
【发布时间】:2015-07-20 09:43:32
【问题描述】:

我有一个 1d int 数组,我想并行化 2 个 for 循环。

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

这是将其“转换”为 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?

【问题讨论】:

  • 互联网上充斥着关于 CUDA 的免费介绍和教程信息。这个问题可以通过阅读一些内容来轻松回答。

标签: c cuda nested


【解决方案1】:

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

为了调用内核foo,您需要指定GridBlock 维度并分配/初始化设备的内存。它看起来像这样。

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

【讨论】:

    猜你喜欢
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多