我无法理解幼稚前缀总和的 cuda 代码。
这是来自https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch39.html的代码 在示例 39-1(天真扫描)中,我们有这样的代码:
__global__ void scan(float *g_odata, float *g_idata, int n)
{
extern __shared__ float temp[]; // allocated on invocation
int thid = threadIdx.x;
int pout = 0, pin = 1;
// Load input into shared memory.
// This is exclusive scan, so shift right by one
// and set first element to 0
temp[pout*n + thid] = (thid > 0) ? g_idata[thid-1] : 0;
__syncthreads();
for (int offset = 1; offset < n; offset *= 2)
{
pout = 1 - pout; // swap double buffer indices
pin = 1 - pout;
if (thid >= offset)
temp[pout*n+thid] += temp[pin*n+thid - offset];
else
temp[pout*n+thid] = temp[pin*n+thid];
__syncthreads();
}
g_odata[thid] = temp[pout*n+thid1]; // write output
}
我的问题是
- 为什么我们需要创建一个共享内存临时?
- 为什么我们需要“pout”和“pin”变量?他们在做什么?既然我们这里只用了一个block,最多1024个线程,那我们能不能只用threadId.x来指定block中的元素呢?
- 在CUDA中,我们是不是用一个线程做一个加法操作?是不是这样,如果我使用 for 循环(给定一个线程用于数组中的一个元素,循环 OpenMP 中的线程或处理器),一个线程可以在一次迭代中完成什么?
- 我之前的两个问题可能看起来很幼稚......我认为关键是我不明白上述实现与伪代码之间的关系如下:
for d = 1 to log2 n do
for all k in parallel do
if k >= 2^d then
x[k] = x[k – 2^(d-1)] + x[k]
这是我第一次使用CUDA,如果有人能回答我的问题,我将不胜感激......