GPU by Example
4 / 16

Threads, blocks, grids

7 min readChapter 4 of 16

A launch asks for thousands of threads. Every one of them runs the same function, so the only thing that makes them useful is knowing which thread they are. Four built-in variables answer that question.

Four variables, one identity#

VariableTypeMeaning
threadIdxuint3This thread's position inside its block
blockIdxuint3This block's position inside the grid
blockDimdim3Threads per block (same for every thread)
gridDimdim3Blocks in the grid (same for every thread)

Each has .x, .y, .z. The values are unsigned, and they are the only information the hardware gives you about where a thread sits. Everything else — array indices, tile coordinates, which row of a matrix to process — you compute from them.

The widget above is the mental model: a grid of boxes, each box a block, each square a thread. Hover any square. The four variables are just coordinates, and the global index is arithmetic on those coordinates.

One dimension: the linear index#

For a 1D launch the formula is:

CUDA C++
int i = blockIdx.x * blockDim.x + threadIdx.x;

With <<<3, 4>>> the grid has 12 threads and the mapping is:

Output
threadIdx.x   0 1 2 3 | 0 1 2 3 | 0 1 2 3
blockIdx.x    0 0 0 0 | 1 1 1 1 | 2 2 2 2
i             0 1 2 3 | 4 5 6 7 | 8 9 10 11

This is the index you feed to a flat array:

scale.cuCUDA C++
__global__ void scale(float* data, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) data[i] *= 2.0f;
}

Two properties matter later:

  • Consecutive threadIdx.x values map to consecutive array elements. That is what makes global memory accesses coalesce (Chapter 13).
  • blockIdx.x * blockDim.x is where this block's slice starts. Blocks partition the array into contiguous chunks.

Two dimensions: matrices without arithmetic gymnastics#

A 2D launch maps naturally onto a 2D array. You compute an x and a y, then flatten them yourself:

matadd.cuCUDA C++
#include <cstdio>
#include <cuda_runtime.h>

__global__ void matAdd(const float* A, const float* B, float* C,
                       int w, int h) {
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    int y = blockIdx.y * blockDim.y + threadIdx.y;
    if (x < w && y < h) {
        int i = y * w + x;          // row-major flattening
        C[i] = A[i] + B[i];
    }
}

int main() {
    const int w = 6, h = 4, n = w * h;
    float *A, *B, *C;
    cudaMallocManaged(&A, n * sizeof(float));
    cudaMallocManaged(&B, n * sizeof(float));
    cudaMallocManaged(&C, n * sizeof(float));

    for (int i = 0; i < n; ++i) {
        A[i] = (float)i;
        B[i] = 10.0f * (float)i;
    }

    dim3 block(4, 2);                       // 8 threads
    dim3 grid((w + block.x - 1) / block.x,
              (h + block.y - 1) / block.y); // 2 x 2 blocks
    matAdd<<<grid, block>>>(A, B, C, w, h);
    cudaDeviceSynchronize();

    printf("grid = (%u, %u), block = (%u, %u)\n",
           grid.x, grid.y, block.x, block.y);
    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) printf("%6.1f", C[y * w + x]);
        printf("\n");
    }
    cudaFree(A); cudaFree(B); cudaFree(C);
    return 0;
}
Outputreference run
grid = (2, 2), block = (4, 2)
   0.0  11.0  22.0  33.0  44.0  55.0
  66.0  77.0  88.0  99.0 110.0 121.0
 132.0 143.0 154.0 165.0 176.0 187.0
 198.0 209.0 220.0 231.0 242.0 253.0

The launch shape and the data shape do not need to match. Here a 6×4 matrix is covered by 2×2 blocks of 4×2 threads: 32 threads for 24 elements, and the x < w && y < h check discards the extra ones. The formulas still do the work.

Output
        x →   0    1    2    3  |  4    5
  y      block(0,0) 4×2          |  block(1,0)
  ↓  0        (0,0) (1,0) ...        (4,0) (5,0)
     1        (0,1) ...              (4,1) (5,1)
     -------------------------------------------
     2      block(0,1)              block(1,1)
     3        ...                    ...

Three dimensions#

Volumes, batches, and 3D images use the third component. The index extends in the obvious way:

CUDA C++
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
int z = blockIdx.z * blockDim.z + threadIdx.z;

int i = (z * height + y) * width + x;

dim3 defaults missing components to 1, so dim3(8, 8) is a 2D block with blockDim.z == 1. Watch the grid limits: gridDim.y and gridDim.z max out at 65,535, while gridDim.x is effectively unbounded.

Threads are linearised, x first#

The hardware does not see a 3D block. It sees a line of threads grouped into warps of 32. The linear position of a thread inside its block is:

CUDA C++
int tid = threadIdx.x
        + threadIdx.y * blockDim.x
        + threadIdx.z * blockDim.x * blockDim.y;

Consequences:

  • threadIdx.x varies fastest. Two threads with adjacent x are adjacent in the warp.
  • A 2D block of (32, 8) has warps that each cover one full row of 32 — usually what you want for row-major data.
  • A block of (8, 8) has warps that span four rows, so a warp's lanes touch four separate cache lines when reading a row-major matrix.
  • If blockDim.x * blockDim.y * blockDim.z is not a multiple of 32, the last warp has idle lanes for the entire kernel.

The widget's warp · lane readout uses exactly this formula. Change block.x to 4 and watch a single warp span several rows.

Blocks have no order#

Here is the rule that shapes every algorithm in this book:

Threads in different blocks may execute in any order, in parallel or in series, and cannot synchronise with each other.

A grid of a million blocks runs on a GPU with, say, 132 SMs. Each SM runs a handful of blocks at a time. When one finishes, the scheduler pulls another from the queue. Nothing promises that block 0 runs first, that block 5 and block 6 overlap, or that all blocks are even resident at once.

Therefore:

  • A block may read only data that existed before the kernel launched, or data it wrote itself.
  • A block cannot wait for another block with __syncthreads() — that only synchronises within one block.
  • Any cross-block dependency needs a second kernel launch, atomics with care, or cooperative groups (Chapter 9).
no_order.cuCUDA C++
// Don't do this: block 1 assumes block 0 has already written.
__global__ void broken(float* data) {
    if (blockIdx.x == 0) data[0] = 1.0f;
    if (blockIdx.x == 1) printf("%f\n", data[0]);  // race
}

The program might print 1.0, might print garbage, and might do different things on different GPUs. This is not a performance detail; it is a correctness rule.

Choosing a block size#

Some practical defaults:

  • 128 or 256 threads for most 1D kernels. They fill an SM without exhausting registers.
  • A multiple of 32, always. 256 is eight warps; 250 is seven warps plus 26 idle lanes.
  • 16×16 = 256 is the classic choice for 2D image and matrix kernels.
  • 1,024 threads is legal but often hurts: one block then occupies a large fraction of the SM, and a single block cannot fill it alone.

The real answer depends on registers and shared memory per thread; Chapter 13 has an occupancy calculator. For now, start at 256 and measure.

Exercises#

  • Launch <<<dim3(2,3), dim3(4,2)>>> and print threadIdx, blockIdx, and the linear tid. Verify the order by hand.
  • Change block in matAdd to (3, 3). How many blocks cover the 6×4 matrix? How many threads are wasted?
  • Write a kernel that fills a 3D array of shape 4 × 3 × 2 with i = (z*3 + y)*4 + x. Print it layer by layer.
  • With block = (8, 8), which threadIdx values share warp 0? Which warp contains (0, 4)?
  • Why is if (x < w && y < h) needed even though the grid was rounded up with ceiling division?

Next: what is actually inside an SM, and why 32 threads is the number that keeps appearing.