CUDA Synchronization: Barriers, Atomics and Warp Shuffles

Chapter 5 — making threads cooperate correctly, then quickly

What you will learn

  • What a data race is and why it gives wrong answers silently
  • The rules for __syncthreads(), and the bugs that break them
  • Atomic operations, and how privatization makes them fast (histogram)
  • Parallel reduction in four steps, from a shared-memory tree to warp shuffles
  • Cooperative groups, and how to synchronize across the whole grid

So far each thread has worked on its own output element. Many problems need threads to combine results: a sum, a histogram, a maximum. As soon as two threads touch the same memory, you need to say in what order things happen. CUDA gives you three tools, from cheapest to most general: warp-level primitives, block-level barriers, and atomic operations.

Data races

A data race happens when two threads access the same address, at least one of them writes, and nothing orders the two accesses. The classic example is a counter:

cuda
1234
__global__ void count(int *counter) {
    (*counter)++;          // read, add 1, write back: three steps, not one
}
// count<<<1000, 256>>>(d_counter) usually leaves far less than 256000 in *counter.

Thousands of threads read the same old value, each adds one, and each writes back the same result. Most increments are lost. The program does not crash or warn; it just computes the wrong number, and the number changes from run to run. The fix depends on scope: threads of one warp, of one block, or of the whole grid.

Block barriers: __syncthreads()

You used __syncthreads() in Chapter 3 to make sure a shared-memory tile was fully loaded before anyone read it. It is a barrier for one block: no thread passes it until all threads of the block have reached it, and memory writes made before the barrier are visible to the whole block after it. The rules:

  • Every thread of the block must reach the same barrier. A barrier inside an if that only some threads enter is undefined behavior: it may hang, or silently synchronize nothing.
  • Don't return early before a barrier. Handle out-of-range threads with a guard around the work, not around the barrier.
  • A barrier is needed on both sides of shared reuse: after writing, before others read; and after reading, before anyone overwrites the same buffer in the next loop iteration.
  • It only works within a block. There is no __syncthreads() across blocks.
cuda
1234567891011
// WRONG: threads with i >= n skip the barrier
if (i < n) {
    tile[threadIdx.x] = in[i];
    __syncthreads();
    out[i] = tile[blockDim.x - 1 - threadIdx.x];
}

// RIGHT: every thread reaches the barrier; only the memory accesses are guarded
tile[threadIdx.x] = (i < n) ? in[i] : 0.0f;
__syncthreads();
if (i < n) out[i] = tile[blockDim.x - 1 - threadIdx.x];

compute-sanitizer --tool racecheck finds shared-memory races, and --tool synccheck finds barriers that not all threads reached. Run both whenever you write a kernel that shares data.

Atomic operations

An atomic operation does read-modify-write on one address as a single indivisible step. atomicAdd(counter, 1) fixes the counter above. CUDA provides atomicAdd, atomicSub, atomicMin, atomicMax, atomicAnd/Or/Xor, atomicExch and atomicCAS (compare-and-swap) on global and shared memory, for 32- and 64-bit integers, and atomicAdd on float and double. Every other atomic can be built from atomicCAS (see exercise 3). All of them return the old value.

Atomics on different addresses run at close to normal memory speed. The cost comes from contention: updates to the same address are serialized. The standard fix is privatization: give each block a private copy in shared memory, let the block's threads update that (fast, and contended only within one block), then merge each block's copy into the global result once.

Worked example: a histogram

A histogram counts how often each byte value appears in a buffer of 16 million bytes. The program runs three versions: a racy one with plain increments, one with global atomics, and one privatized in shared memory. It compares the last two with a CPU result.

histogram.cu
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define CUDA_CHECK(call)                                                   \
    do {                                                                   \
        cudaError_t err_ = (call);                                         \
        if (err_ != cudaSuccess) {                                         \
            fprintf(stderr, "CUDA error %s at %s:%d\n",                     \
                    cudaGetErrorString(err_), __FILE__, __LINE__);         \
            exit(1);                                                       \
        }                                                                  \
    } while (0)

#define BINS 256

// 1. Racy: plain increments on global memory lose updates.
__global__ void histRacy(const unsigned char *data, int n, unsigned int *bins) {
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x)
        bins[data[i]]++;
}

// 2. Correct: one global atomic per element.
__global__ void histGlobal(const unsigned char *data, int n, unsigned int *bins) {
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x)
        atomicAdd(&bins[data[i]], 1u);
}

// 3. Privatized: each block counts in shared memory, then merges once.
__global__ void histShared(const unsigned char *data, int n, unsigned int *bins) {
    __shared__ unsigned int local[BINS];
    for (int b = threadIdx.x; b < BINS; b += blockDim.x) local[b] = 0;
    __syncthreads();                                  // all zeros written before anyone counts

    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x)
        atomicAdd(&local[data[i]], 1u);
    __syncthreads();                                  // all counts done before merging

    for (int b = threadIdx.x; b < BINS; b += blockDim.x)
        if (local[b]) atomicAdd(&bins[b], local[b]);
}

int main() {
    const int n = 1 << 24;
    unsigned char *h = (unsigned char *)malloc(n);
    unsigned int seed = 12345;
    for (int i = 0; i < n; i++) {                     // skewed data, like text: low values are common
        seed = seed * 1664525u + 1013904223u;
        h[i] = (unsigned char)(((seed >> 16) & 0xFF) * ((seed >> 8) & 0xFF) >> 8);
    }
    unsigned int ref[BINS] = {0}, out[BINS];
    for (int i = 0; i < n; i++) ref[h[i]]++;

    unsigned char *d_data; unsigned int *d_bins;
    CUDA_CHECK(cudaMalloc(&d_data, n));
    CUDA_CHECK(cudaMalloc(&d_bins, BINS * sizeof(unsigned int)));
    CUDA_CHECK(cudaMemcpy(d_data, h, n, cudaMemcpyHostToDevice));

    int sms; CUDA_CHECK(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, 0));
    const int threads = 256, blocks = sms * 8;
    const char *names[] = {"racy", "global atomics", "shared atomics"};
    cudaEvent_t a, b;
    CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b));

    bool ok = true;
    for (int v = 0; v < 3; v++) {
        float ms = 0;
        for (int rep = 0; rep < 2; rep++) {           // rep 0 is a warm-up
            CUDA_CHECK(cudaMemset(d_bins, 0, BINS * sizeof(unsigned int)));
            CUDA_CHECK(cudaEventRecord(a));
            if (v == 0) histRacy<<<blocks, threads>>>(d_data, n, d_bins);
            if (v == 1) histGlobal<<<blocks, threads>>>(d_data, n, d_bins);
            if (v == 2) histShared<<<blocks, threads>>>(d_data, n, d_bins);
            CUDA_CHECK(cudaEventRecord(b));
            CUDA_CHECK(cudaEventSynchronize(b));
            CUDA_CHECK(cudaEventElapsedTime(&ms, a, b));
        }
        CUDA_CHECK(cudaMemcpy(out, d_bins, sizeof(out), cudaMemcpyDeviceToHost));
        long long total = 0; int wrong = 0;
        for (int k = 0; k < BINS; k++) { total += out[k]; if (out[k] != ref[k]) wrong++; }
        printf("%-15s %7.3f ms  counted %9lld of %d  wrong bins: %d\n", names[v], ms, total, n, wrong);
        if (v > 0) ok = ok && wrong == 0;             // the racy version is expected to be wrong
    }
    printf(ok ? "PASS\n" : "FAIL\n");
    CUDA_CHECK(cudaFree(d_data)); CUDA_CHECK(cudaFree(d_bins));
    free(h);
    return 0;
}

The racy version loses most of its counts, and a different number each run. Global atomics are correct, but threads all over the GPU fight over the few common bins. Shared atomics keep that fight inside one block, so the privatized version is much faster: over 40× on an RTX 3070 with this skewed input. This step-by-step style of improving one kernel is how most CUDA optimization work goes.

Parallel reduction in four steps

A reduction combines many values into one: a sum, maximum or dot product. It is the best-known exercise in CUDA optimization, because each step teaches something. The plan is the same in every version: each block reduces its part of the input to one partial sum, and one thread per block adds that partial into the result with atomicAdd.

317041637213320525stride 4: threads 0–3 add element t + 4stride 2: threads 0–1 add element t + 2stride 1: thread 0 adds element 1
Sequential addressing: the active threads are always the first ones, so whole warps finish together instead of every warp diverging.
  1. Interleaved addressing. At step s, threads whose index is a multiple of 2s add their neighbor s away. Correct, but tid % (2*s) == 0 leaves scattered active threads in every warp: divergence from Chapter 4.
  2. Sequential addressing. Threads 0 … s-1 add element t + s, halving s each step (the figure). Active threads are packed together, so idle warps drop out completely.
  3. Warp shuffle. Within a warp, threads can read each other's registers with __shfl_down_sync. No shared memory, no barrier. Each warp reduces its 32 values in 5 steps; only the 8 warp results go through shared memory.
  4. More work per thread. With one element per thread, most of the time goes into the reduction tree and 65,536 atomics. A grid-stride loop lets each thread first add up many elements in a register, so the tree runs once per thread instead of once per element.
reduction.cu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
#include <cstdio>
#include <cstdlib>
#include <cmath>

#define CUDA_CHECK(call)                                                   \
    do {                                                                   \
        cudaError_t err_ = (call);                                         \
        if (err_ != cudaSuccess) {                                         \
            fprintf(stderr, "CUDA error %s at %s:%d\n",                     \
                    cudaGetErrorString(err_), __FILE__, __LINE__);         \
            exit(1);                                                       \
        }                                                                  \
    } while (0)

#define THREADS 256

// v1: interleaved addressing (divergent)
__global__ void reduceInterleaved(const float *x, int n, float *out) {
    __shared__ float s[THREADS];
    int tid = threadIdx.x, i = blockIdx.x * blockDim.x + tid;
    s[tid] = (i < n) ? x[i] : 0.0f;
    __syncthreads();
    for (int stride = 1; stride < blockDim.x; stride *= 2) {
        if (tid % (2 * stride) == 0) s[tid] += s[tid + stride];
        __syncthreads();
    }
    if (tid == 0) atomicAdd(out, s[0]);
}

// v2: sequential addressing (active threads packed at the front)
__global__ void reduceSequential(const float *x, int n, float *out) {
    __shared__ float s[THREADS];
    int tid = threadIdx.x, i = blockIdx.x * blockDim.x + tid;
    s[tid] = (i < n) ? x[i] : 0.0f;
    __syncthreads();
    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) s[tid] += s[tid + stride];
        __syncthreads();
    }
    if (tid == 0) atomicAdd(out, s[0]);
}

// Sum of the 32 values held by one warp. All 32 lanes must call it.
__device__ float warpSum(float v) {
    for (int offset = 16; offset > 0; offset >>= 1)
        v += __shfl_down_sync(0xffffffffu, v, offset);
    return v;                                         // lane 0 holds the total
}

// Shuffle within each warp, then combine the warp sums.
__device__ void blockSumToGlobal(float v, float *out) {
    __shared__ float warpSums[THREADS / 32];
    int lane = threadIdx.x % 32, warp = threadIdx.x / 32;
    v = warpSum(v);
    if (lane == 0) warpSums[warp] = v;
    __syncthreads();
    if (warp == 0) {
        v = (lane < blockDim.x / 32) ? warpSums[lane] : 0.0f;
        v = warpSum(v);
        if (lane == 0) atomicAdd(out, v);
    }
}

// v3: one element per thread, warp shuffles
__global__ void reduceShuffle(const float *x, int n, float *out) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    blockSumToGlobal((i < n) ? x[i] : 0.0f, out);     // no early return: every lane joins the shuffle
}

// v4: grid-stride loop first, so each thread sums many elements in a register
__global__ void reduceCoarse(const float *x, int n, float *out) {
    float v = 0.0f;
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x)
        v += x[i];
    blockSumToGlobal(v, out);
}

int main() {
    const int n = 1 << 24;
    const size_t bytes = n * sizeof(float);
    float *h = (float *)malloc(bytes);
    double ref = 0.0;
    for (int i = 0; i < n; i++) { h[i] = ((i * 2654435761u) >> 22) / 1024.0f; ref += h[i]; }

    float *d_x, *d_out;
    CUDA_CHECK(cudaMalloc(&d_x, bytes));
    CUDA_CHECK(cudaMalloc(&d_out, sizeof(float)));
    CUDA_CHECK(cudaMemcpy(d_x, h, bytes, cudaMemcpyHostToDevice));

    int sms; CUDA_CHECK(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, 0));
    const int fullGrid = (n + THREADS - 1) / THREADS, coarseGrid = sms * 8;
    const char *names[] = {"1 interleaved", "2 sequential", "3 warp shuffle", "4 + grid-stride"};
    cudaEvent_t a, b;
    CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b));

    bool ok = true;
    for (int v = 0; v < 4; v++) {
        float total = 0;
        const int reps = 10;
        for (int rep = -1; rep < reps; rep++) {          // rep -1 is a warm-up
            CUDA_CHECK(cudaMemset(d_out, 0, sizeof(float)));
            CUDA_CHECK(cudaEventRecord(a));
            if (v == 0) reduceInterleaved<<<fullGrid, THREADS>>>(d_x, n, d_out);
            if (v == 1) reduceSequential<<<fullGrid, THREADS>>>(d_x, n, d_out);
            if (v == 2) reduceShuffle<<<fullGrid, THREADS>>>(d_x, n, d_out);
            if (v == 3) reduceCoarse<<<coarseGrid, THREADS>>>(d_x, n, d_out);
            CUDA_CHECK(cudaEventRecord(b));
            CUDA_CHECK(cudaEventSynchronize(b));
            float ms; CUDA_CHECK(cudaEventElapsedTime(&ms, a, b));
            if (rep >= 0) total += ms;
        }
        float sum; CUDA_CHECK(cudaMemcpy(&sum, d_out, sizeof(float), cudaMemcpyDeviceToHost));
        double ms = total / reps, relErr = fabs(sum - ref) / ref;
        printf("%-16s %6.3f ms  %6.1f GB/s  sum %.1f  (rel. error %.1e)\n",
               names[v], ms, bytes / ms / 1e6, sum, relErr);
        ok = ok && relErr < 1e-4;
    }
    printf("CPU reference    sum %.1f\n", ref);
    printf(ok ? "PASS\n" : "FAIL\n");
    CUDA_CHECK(cudaFree(d_x)); CUDA_CHECK(cudaFree(d_out));
    free(h);
    return 0;
}

Read the GB/s column against your GPU's memory bandwidth (the occupancy program in Chapter 4 prints it). A reduction reads each element once and does one addition per element, so it is limited by memory bandwidth. The last version should come close to the hardware limit; at that point the kernel is finished, and further tricks cannot help much.

Floating-point sums are not deterministic

Float addition is not associative, and atomics finish in a different order each run, so the last digits of the GPU sum can change from run to run and differ from the CPU sum. That is why the program compares with a relative tolerance. If you need bit-identical results, write the block partials to an array and reduce them in a fixed order in a second kernel.

Warp-level primitives

Warp shuffles exchange registers between the threads of a warp without shared memory. All take a mask of participating lanes (0xffffffff for the full warp), and every lane named in the mask must execute the call:

FunctionEach lane gets
__shfl_sync(mask, v, src)v from lane src (broadcast)
__shfl_down_sync(mask, v, d)v from lane id + d
__shfl_up_sync(mask, v, d)v from lane id − d (prefix scans)
__shfl_xor_sync(mask, v, m)v from lane id ^ m (all lanes get the total)
__ballot_sync(mask, pred)a 32-bit mask of the lanes where pred is true
__any_sync / __all_syncwhether any / all lanes have pred true
__syncwarp(mask)a barrier and memory fence for the lanes in mask

As Chapter 4 explained, threads of a warp are not guaranteed to run in lockstep. The old trick of finishing a reduction with a volatile shared array and no synchronization is a data race on Volta and newer GPUs. Use shuffles or __syncwarp() instead.

Cooperative groups

Cooperative groups (header <cooperative_groups.h>) give names to sets of threads, so code says which threads take part instead of relying on hidden assumptions. A thread block, a 32-thread tile and the whole grid are all groups with a sync() method. The cg::reduce helper replaces the hand-written shuffle loop:

cuda
12345678910111213141516
#include <cooperative_groups.h>
#include <cooperative_groups/reduce.h>
namespace cg = cooperative_groups;

__global__ void sumKernel(const float *x, int n, float *out) {
    cg::thread_block block = cg::this_thread_block();
    cg::thread_block_tile<32> warp = cg::tiled_partition<32>(block);

    float v = 0.0f;
    for (int i = block.group_index().x * block.size() + block.thread_rank(); i < n;
         i += gridDim.x * block.size())
        v += x[i];

    v = cg::reduce(warp, v, cg::plus<float>());   // warp-level sum
    if (warp.thread_rank() == 0) atomicAdd(out, v);
}

Grid-wide synchronization. The usual way to make all blocks wait for each other is to end the kernel: launches in the same stream run in order, and the next kernel sees everything the previous one wrote. Inside a single kernel, cg::this_grid().sync() works only if the kernel is started with cudaLaunchCooperativeKernel and all of its blocks fit on the GPU at the same time. Otherwise blocks waiting at the barrier would block the ones that never got to run.

Memory fences. __threadfence() makes a thread's earlier writes visible to the whole GPU before its later writes. It does not wait for other threads. You need it in patterns where one block publishes data and then raises a flag for another block, such as the "last block finishes the reduction" pattern.

Summary

  • Unordered access to shared data with at least one write is a data race. It gives wrong results quietly.
  • __syncthreads() must be reached by every thread of the block. Guard the work, not the barrier.
  • Atomics are correct and cheap without contention. Privatize into shared memory to avoid contention.
  • Reductions: pack active threads together, finish with warp shuffles, and do more work per thread until you reach memory bandwidth.
  • Warps are not lockstep: use *_sync primitives with a correct mask, never volatile tricks.
  • Synchronize the whole grid by ending the kernel, or with a cooperative launch.

Exercises

1. Count the idle lanes. In the interleaved reduction with 256 threads, how many lanes of warp 0 do useful work at stride 1, 2 and 4? Compare with the sequential version.

Solution

Interleaved: 16 lanes at stride 1 (even indices), 8 at stride 2, 4 at stride 4, but all 8 warps stay busy every step because every warp has active lanes. Sequential: at stride 128, threads 0–127 (warps 0–3) work fully and warps 4–7 are idle; at stride 64 only warps 0–1 work. Inactive warps cost nothing, while partly active warps cost a full warp step.

2. Contention. In histogram.cu, fill the input with the same byte everywhere (h[i] = 7). How do the three times change?

Solution

Global atomics get much slower: every thread on the GPU now updates one address, so all updates are serialized. Shared atomics also slow down, but contention is limited to one block per copy, so the gap between the two grows. A further trick is to accumulate repeated values in a register first and issue one atomic per run of equal values.

3. Build your own atomic. Write atomicMaxFloat(float *addr, float v) using atomicCAS.

Solution
cuda
12345678910
__device__ float atomicMaxFloat(float *addr, float v) {
    int *a = (int *)addr;
    int old = *a, assumed;
    do {
        assumed = old;
        if (__int_as_float(assumed) >= v) break;            // already larger: nothing to do
        old = atomicCAS(a, assumed, __float_as_int(v));     // swap only if unchanged since we read it
    } while (old != assumed);                               // someone else wrote first: retry
    return __int_as_float(old);
}

The loop retries until no other thread changed the value between the read and the swap. Every CUDA atomic that the hardware lacks is built this way.

Check your understanding

Can you call __syncthreads() inside if (threadIdx.x < 128) when the block has 256 threads?

No. Threads 128–255 never reach that barrier. The behavior is undefined: it can hang or fail to synchronize. Move the barrier outside the branch.

Why does reduceShuffle compute v = (i < n) ? x[i] : 0 instead of returning early when i >= n?

The shuffle uses a full mask, so all 32 lanes must call it, and the block later reaches a __syncthreads(). Returning early would break both. A zero does not change the sum.

Further reading & credits

The chapter order and topic coverage of this course draw on the OLCF / NERSC CUDA Training Series, the NVIDIA Accelerated Computing Hub CUDA C++ tutorial, the GPU MODE lectures (Apache-2.0) and Simon Boehm's CUDA matrix multiplication worklog (code MIT). The text and example programs on this page are original and were tested on NVIDIA Turing and Ampere GPUs.

Next: keeping the GPU and the copy engines busy at the same time. Continue to Streams and Concurrency.

Practice These Concepts

Reinforce what you just learned with hands-on GPU coding challenges.

Parallel Histogram Computationmedium

Compute a histogram of 256 bins for an array of 10,000 random byte values (0-255). Use atomic operations to avoid race conditions when multiple threads update the same bin.

Sign in to track your progress across challenges.