GPU by Example
9 / 16

Synchronization

6 min readChapter 9 of 16

Threads in a block cooperate. Cooperation without ordering is a race. CUDA gives you three levels of synchronisation, and using the wrong one is either useless or fatal.

The barrier#

__syncthreads() is a block-wide barrier and memory fence. Every thread that calls it waits until every other thread in the block has called it; then all memory writes made before the barrier become visible after it.

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

__global__ void rotate(const float* in, float* out) {
    __shared__ float tile[8];

    int base = blockIdx.x * blockDim.x;
    tile[threadIdx.x] = in[base + threadIdx.x];
    __syncthreads();                                  // writes are visible

    out[base + threadIdx.x] = tile[(threadIdx.x + 1) % blockDim.x];
}

int main() {
    const int n = 16;
    float *in, *out;
    cudaMallocManaged(&in, n * sizeof(float));
    cudaMallocManaged(&out, n * sizeof(float));
    for (int i = 0; i < n; ++i) in[i] = (float)i;

    rotate<<<2, 8>>>(in, out);
    cudaDeviceSynchronize();

    for (int i = 0; i < n; ++i) printf("%.0f ", out[i]);
    printf("\n");
    cudaFree(in); cudaFree(out);
    return 0;
}
Outputreference run
1 2 3 4 5 6 7 0 9 10 11 12 13 14 15 8

Each block rotates its own eight values. Without the barrier, thread 0 could read tile[1] before thread 1 has written it — the output would depend on warp scheduling.

The rules#

There are only a few, but breaking one gives undefined behaviour rather than a helpful error:

  • Every thread in the block must reach the same __syncthreads(). Not "most threads". All of them.
  • Never put it inside divergent control flow unless the condition is uniform across the block.
  • Never use it to wait for another block. It only synchronises the block that calls it.
  • It is not free. A barrier drains the block's pipelines and costs tens of cycles plus the slowest thread's delay.

This is wrong:

CUDA C++
__global__ void broken(const float* in, float* out, int n) {
    __shared__ float tile[256];
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    if (i < n) {
        tile[threadIdx.x] = in[i];
    }
    __syncthreads();               // some threads may have returned already
    out[i] = tile[0];
}

If the partial block has threads with i >= n, they skip the write but still reach the barrier — that part is fine. The illegal version returns early:

CUDA C++
if (i >= n) return;                // <-- thread is gone
tile[threadIdx.x] = in[i];
__syncthreads();                   // the remaining threads wait forever

Clamp the index instead, or compute a safe value and keep every thread alive until after the barrier.

Warp-level sync#

Since Volta, threads in a warp have independent scheduling. Lanes may drift apart, so a warp is not a free barrier. When lanes exchange data with shuffle instructions or write to the same shared addresses, use __syncwarp():

CUDA C++
unsigned mask = 0xffffffff;          // all 32 lanes
int v = __shfl_down_sync(mask, value, 1);
__syncwarp(mask);

__shfl_*_sync already takes a mask and synchronises the named lanes before exchanging. __syncwarp() is for the cases where you need an explicit rendezvous. It is much cheaper than __syncthreads() because it does not involve the whole block.

Memory fences are not barriers#

A fence orders memory operations; it does not make anyone wait.

FunctionOrders
__threadfence_block()This thread's accesses, as seen by its block
__threadfence()This thread's accesses, as seen by the whole grid
__threadfence_system()This thread's accesses, as seen by host and peer GPUs

A producer-consumer pattern across blocks needs both a fence and an atomic flag — and even then, the consumer must poll. Most of the time, the right answer is a second kernel launch instead.

CUDA C++
// Block 0 produces, everyone else consumes: do NOT do this casually.
__global__ void producerConsumer(int* data, int* flag) {
    if (blockIdx.x == 0) {
        data[0] = 42;
        __threadfence();                 // make the write visible first
        atomicExch(flag, 1);             // then publish
    } else if (blockIdx.x == 1) {
        while (atomicAdd(flag, 0) == 0) {}   // spin (can deadlock!)
        printf("%d\n", data[0]);
    }
}

This can deadlock if block 1 is scheduled before block 0 and block 0 never gets an SM. There is no forward-progress guarantee between blocks. Prefer separate kernels.

Grid-wide sync with cooperative groups#

If you genuinely need all blocks to rendezvous, CUDA offers cooperative launches. All blocks must be resident at the same time, so the grid size is bounded by occupancy.

grid_sync.cuCUDA C++
#include <cooperative_groups.h>
namespace cg = cooperative_groups;

__global__ void allBlocks(int* data) {
    cg::grid_group grid = cg::this_grid();

    data[blockIdx.x] = blockIdx.x;
    grid.sync();                        // every block has written

    if (blockIdx.x == 0) {
        int sum = 0;
        for (int i = 0; i < gridDim.x; ++i) sum += data[i];
        printf("sum of block ids = %d\n", sum);
    }
}

int main() {
    int* d;
    cudaMallocManaged(&d, 4 * sizeof(int));

    void* args[] = {&d};
    cudaLaunchCooperativeKernel((void*)allBlocks, dim3(4), dim3(128),
                                args, 0, 0);
    cudaDeviceSynchronize();
    cudaFree(d);
}

Requirements:

  • The device must support cooperative launch: cudaDevAttrCooperativeLaunch.
  • The grid must fit on the GPU simultaneously. Compute the maximum with cudaOccupancyMaxActiveBlocksPerMultiprocessor and multiply by the SM count.
  • Launch with cudaLaunchCooperativeKernel, not <<<>>>.
  • grid.sync() is expensive — it is a global barrier, not a warp trick.

For most algorithms, two kernel launches are simpler, faster, and easier to debug. Use grid sync when the intermediate state is large and you want to avoid a round trip through the host.

Structuring around barriers#

Barriers serialise phases. Good kernels have few, wide phases:

Output
load tile  →  __syncthreads()  →  compute  →  __syncthreads()  →  store

Bad kernels put a barrier inside a loop where different threads do different amounts of work:

CUDA C++
for (int k = 0; k < n; ++k) {
    if (threadIdx.x < k) { ... }
    __syncthreads();          // the slowest lane sets the pace for everyone
}

If you find yourself adding a barrier to fix a race, ask whether the algorithm can be split into two kernels instead. Often it can, and the result is faster.

Exercises#

  • Remove __syncthreads() from rotate.cu, compile with -O3, and run it 100 times. Does it ever fail? Why is that not evidence that it is correct?
  • Write a version that returns early for i >= n and still compiles. Run it with n not divisible by the block size. What happens?
  • Replace the two __syncthreads() in the tiled matmul with __syncwarp(). Explain why the result is wrong.
  • Why can a cooperative grid not contain more blocks than fit simultaneously? What would grid.sync() mean otherwise?
  • Use __syncthreads_count(predicate) to count how many threads in a block satisfy a condition. What does it return to every thread?

Next: when many threads update the same address, barriers are not enough — you need atomics.