GPU Programming
Why does the CUDA kernel above include "if (i < n)"?
__global__ void add(float *c, const float *a,
const float *b, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n)
c[i] = a[i] + b[i];
}
- ASo that surplus threads do not read or write beyond the array when there are more threads than elements
- BTo keep the sums from exceeding n
- CTo double the GPU's speed
Show answer and explanation
Answer: A. So that surplus threads do not read or write beyond the array when there are more threads than elements
Threads are launched in whole blocks, so unless the element count is a multiple of the block size, there are more threads than elements. Writing without checking the index would corrupt memory beyond the allocated arrays or fault on an illegal access. The "i < n" check is an almost universal pattern in GPU kernels.
- A. Correct. It handles the surplus from rounding up the block count.
- B. It checks the index range, not the size of the values.
- C. It is for correctness, not speed.