CUDA内核调用一个简单的示例

时间:2012-07-20 11:26:21

标签: cuda

这是 cuda的第一个并行代码

任何人都可以向我描述内核调用:<<< N,1>>>

这是重要的代码:

#define N   10

__global__ void add( int *a, int *b, int *c ) {
    int tid = blockIdx.x;    // this thread handles the data at its thread id
    if (tid < N)
        c[tid] = a[tid] + b[tid];
}

int main( void ) {
    int a[N], b[N], c[N];
    int *dev_a, *dev_b, *dev_c;

    // allocate the memory on the GPU
    // fill the arrays 'a' and 'b' on the CPU
    // copy the arrays 'a' and 'b' to the GPU

    add<<<N,1>>>( dev_a, dev_b, dev_c );

    // copy the array 'c' back from the GPU to the CPU
    // display the results
    // free the memory allocated on the GPU

    return 0;
}

为什么使用<<< N , 1 >>>表示我们在每个块中使用了N个块和1个线程?因为我们可以写这个<<< 1 , N >>>并在这个块中使用1个块和N个线程来进行更多优化。

1 个答案:

答案 0 :(得分:4)

对于这个小例子,没有特别的理由(正如巴特在评论中已经告诉过你的那样)。但是对于更大,更现实的示例,您应该始终牢记每个块的线程数量是有限的。也就是说,如果您使用N = 10000,则无法再使用<<<1,N>>>,但<<<N,1>>>仍可使用。