【发布时间】:2012-07-20 11:26:21
【问题描述】:
这是 cuda 的第一个并行代码示例。
谁能描述一下内核调用:>>
这是重点代码:
#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个线程来进行更多优化。
【问题讨论】:
-
没有特别的原因。这是本书中第一个尝试解释 GPU 向量和的示例。在这一点上,他们几乎没有考虑过最佳性能或任何此类概念。这是一个简单的说明性示例。就这样。正如一开始的目标所说“您将使用 CUDA C 编写您的第一个并行代码”。
标签: cuda