I am learning the cuda project demo reduction, and I have a question about the following code:
in the function:
template <class T, unsigned int blockSize>
global void
FUNC(reduce4)(T *g_idata, T *g_odata, unsigned int n)
{
SharedMemory smem;
T *sdata = smem.getPointer();
// perform first level of reduction,
// reading from global memory, writing to shared memory
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x*(blockDim.x*2) + threadIdx.x;
sdata[tid] = (i < n) ? g_idata[i] : 0;
if (i + blockSize < n)
sdata[tid] += g_idata[i+blockSize];
__syncthreads();
// do reduction in shared mem
for(unsigned int s=blockDim.x/2; s>32; s>>=1)
{
if (tid < s)
{
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
#ifndef DEVICE_EMULATION
if (tid < 32)
#endif
{
if (blockSize >= 64) { sdata[tid] += sdata[tid + 32]; EMUSYNC; }
if (blockSize >= 32) { sdata[tid] += sdata[tid + 16]; EMUSYNC; }
if (blockSize >= 16) { sdata[tid] += sdata[tid + 8]; EMUSYNC; }
if (blockSize >= 8) { sdata[tid] += sdata[tid + 4]; EMUSYNC; }
if (blockSize >= 4) { sdata[tid] += sdata[tid + 2]; EMUSYNC; }
if (blockSize >= 2) { sdata[tid] += sdata[tid + 1]; EMUSYNC; }
}
// write result for this block to global mem
if (tid == 0) g_odata[blockIdx.x] = sdata[0];
}
When unrolling the last 6 iterations, the last few lines I think should be:
if (tid<32) { sdata[tid] += sdata[tid + 32]; }
if (tid<16) { sdata[tid] += sdata[tid + 16]; }
if (tid<8 ) { sdata[tid] += sdata[tid + 8]; }
if (tid<4 ) { sdata[tid] += sdata[tid + 4]; }
if (tid<2 ) { sdata[tid] += sdata[tid + 2]; }
if (tid<1 ) { sdata[tid] += sdata[tid + 1]; }
I really don’t unstand why the programmer do not need to check “if(tid<s)”. Can anyone tell me?
Thanks.