L2 Intermediate · Module 4: CUDA programming fundamentals

4.5Race conditions and correctness

When thousands of threads update the same memory, a simple counter++ goes badly wrong. This chapter shows a data race in action, fixes it with atomics, then makes the fix fast, and explains why parallel floating-point sums aren't reproducible.

GPU required (Colab or a rented GPU)~20 min

By the end you will be able to

  • ✓Explain why a read-modify-write from many threads is a data race
  • ✓Fix a race with atomic operations, and reduce their contention with block-level aggregation
  • ✓Explain why atomic floating-point sums are non-deterministic, and why that matters for inference
  • ✓Use compute-sanitizer to find memory errors and shared-memory races

Suppose every thread checks one element and, if it is positive, adds one to a shared counter:

if (x[i] > 0) (*count)++;

On a CPU with one thread this is fine. On a GPU it is a data race.

Why it breaks

(*count)++ is three steps: read the counter into a register, add one, write it back. Thousands of threads do this at once:

TimeThread AThread Bcount in memory
1read → 55
2read → 55
3add → 6add → 65
4write 66
5write 66 (should be 7)

One increment is lost. With millions of threads, almost all of them are:

output (RTX 3050 6GB Laptop)
Counting positives among 16777216 elements (expected 5592406):
naive count = 5281 (WRONG) 0.413 ms
atomic count = 5592406 (correct) 0.441 ms
block count = 5592406 (correct) 0.413 ms

The naive kernel counted 5,281 out of 5.6 million: over 99.9% of the increments were lost. Note that it didn’t crash or warn. Races produce plausible-looking wrong numbers.

Atomics

An atomic operation makes the read-modify-write indivisible: the memory system performs it as one step, so no other thread can slip in between.

if (x[i] > 0) atomicAdd(count, 1);

CUDA provides atomicAdd, atomicMax, atomicMin, atomicExch, and atomicCAS (compare-and-swap, which can build any other atomic, 5.3). They work on global and shared memory.

Contention, and how to avoid it

When millions of threads hit one address, the atomics serialize on it. Two standard fixes:

  • Aggregate per block. Count into a __shared__ variable (shared-memory atomics are cheap), then do one global atomicAdd per block. 65,536 global atomics instead of 5.6 million.
  • Aggregate per warp. Combine the 32 lanes’ contributions with warp shuffles (5.2) and let one lane do the atomic.

In the lab, the plain atomic version is barely slower than the others. The likely reason is that the compiler already applies warp aggregation to this simple pattern (every lane adding 1 to the same address) on its own. With more complex updates, such as a histogram where lanes hit different addresses, it can’t, and explicit aggregation can matter a lot (5.5).

Tools: let the machine find bugs

compute-sanitizer ships with the CUDA toolkit and runs your program under instrumentation:

ToolFinds
compute-sanitizer ./app (memcheck)out-of-bounds and misaligned accesses, use of freed memory
--tool racecheckraces on shared memory, such as a missing __syncthreads (4.4)
--tool synccheckinvalid barrier use, such as __syncthreads in divergent code
--tool initcheckreads of uninitialized device memory

racecheck does not detect races on global memory like the counter above; those you prevent by design. Run your kernels under the sanitizer at least once, on small inputs: it is slow, but it finds bugs that would otherwise show up as rare wrong answers in production.

Lab: a race, then two fixes 🔴

Terminal window
cd labs/m04/4.5 && nvcc -O2 -arch=native race.cu -o race && ./race

Sources

Check your understanding

0 / 4 answered
  1. 1.Why does (*count)++ from many threads give the wrong answer?

  2. 2.What does atomicAdd guarantee?

  3. 3.How does per-block aggregation reduce atomic contention?

  4. 4.Why can a float sum done with atomicAdd change between runs?