L2 Intermediate · Module 5: Parallel patterns
5.3Atomics and compare-and-swap
Atomics let many threads update shared memory safely, but their speed depends almost entirely on how many threads hit the same address. Compare-and-swap builds any atomic you need, at a price that grows with contention. This chapter measures both and ends with a one-launch sum that gives the same bits every time.
By the end you will be able to
- ✓Predict atomic throughput from the number of distinct addresses being updated
- ✓Build an atomic operation the hardware lacks from atomicCAS, and explain when its loop retries
- ✓Choose between hardware atomics, bit tricks and warp pre-reduction to cut contention
- ✓Use the last-block pattern with __threadfence for a deterministic one-pass reduction
4.5 introduced atomics as the fix for a data race: atomicAdd makes a read-modify-write indivisible.
This chapter is about what they cost and what to do when the operation you need doesn’t exist.
Where atomics happen
A global-memory atomic doesn’t run on the SM. The SM sends the request to the L2 cache, and the L2 slice that owns the address does the read-modify-write itself. Two consequences:
- Atomics on different addresses are spread over many L2 slices and run in parallel.
- Atomics on the same address queue at one slice and run one after another.
Shared-memory atomics run on the SM, are much cheaper, and only contend within one block.
Measured: contention is everything
Each of 16 M threads adds to one of counters (thread uses counter ):
16777216 atomicAdds into K counters (thread i adds to counter i % K): K time atomics / ns 1 9.220 ms 1.8 PASS 2 9.000 ms 1.9 PASS 32 1.420 ms 11.8 PASS 1024 0.527 ms 31.8 PASS 32768 0.525 ms 31.9 PASS 1048576 1.658 ms 10.1 PASS 16777216 1.660 ms 10.1 PASS- One address: 1.8 atomics per nanosecond. Every update waits in line.
- 1,024 to 32,768 addresses: 32 per ns, 18× faster. At this point the kernel is limited by reading its 64 MB of input (0.527 ms ≈ 127 GB/s), not by the atomics at all.
- A million addresses or more: back down to 10 per ns. The counters no longer fit in the 2 MB L2 cache, so each atomic also costs a trip to DRAM.
So, to make atomics fast, spread them out, but keep the target small enough to stay in cache. The histogram in 5.5 is exactly this trade-off.
Compare-and-swap: build your own atomic
CUDA has atomicMax for integers but not for floats. Every missing atomic can be built from one primitive:
unsigned atomicCAS(unsigned* addr, unsigned compare, unsigned val);// atomically: old = *addr; if (old == compare) *addr = val; return old;The recipe: read the current value, compute the new one, and swap it in only if nobody changed the word meanwhile. If someone did, CAS returns what is really there, and you try again with that.
__device__ float atomic_max_cas(float* addr, float val) { unsigned* a = reinterpret_cast<unsigned*>(addr); unsigned old = *a, assumed; do { assumed = old; if (__uint_as_float(assumed) >= val) break; // already big enough: don't write at all old = atomicCAS(a, assumed, __float_as_uint(val)); } while (old != assumed); // lost the race: retry with the new value return __uint_as_float(old);}This is a lock-free loop: some thread always makes progress, and a thread retries only because another one succeeded. Its cost depends on the data:
Max of 16777216 floats into one address: CAS loop, random order 0.559 ms PASS CAS retries: 6514 CAS loop, ascending order 7.291 ms PASS CAS retries: 1301020 integer atomicMax, ascending order 0.527 ms PASS warp max, then CAS, ascending order 1.086 ms PASSWith random input, the running max quickly gets large, and almost every thread takes the early break without writing anything: 6,514
retries in 16 M elements. With ascending input, every value is a new maximum, every thread tries to write, and 1.3 M CAS operations fail
and retry. The same code runs 13× slower.
Two ways out:
- A bit trick. For non-negative floats, the IEEE-754 bit patterns sort in the same order as the values, so integer
atomicMaxon the bits gives the float max, in one hardware atomic. (Negative values need the sign handled; see the exercises.) - Reduce first. A warp max with shuffles (5.2) cuts the number of CAS loops 32×.
Both work for many other cases too. Reduce locally first, and use an atomic only for the last step.
The last-block pattern: one launch, fixed order
5.2 ended with a one-launch sum whose last bits changed from run to run, because blocks added their totals with
atomicAdd in whatever order they finished. The fix uses an atomic only to decide who goes last, never to add floats:
float v = block_sum(grid_partial(x, n));__shared__ bool am_last;if (threadIdx.x == 0) { partials[blockIdx.x] = v; __threadfence(); // my partial is visible to every block before... am_last = atomicAdd(ticket, 1) == gridDim.x - 1; // ...I take a ticket}__syncthreads();if (am_last) { // the last block sums all partials, in index order float t = 0.0f; for (int b = threadIdx.x; b < gridDim.x; b += BLOCK) t += partials[b]; t = block_sum(t); if (threadIdx.x == 0) { *out = t; *ticket = 0; }}__threadfence() makes this block’s earlier writes visible to the whole GPU before anything it writes afterwards. Without it, the last block
could take its ticket, read partials[b], and see a stale value that hasn’t reached L2 yet.
One-launch float sum of 16777216 values, 6 runs each (bit patterns of the result): atomicAdd per block 4b0002c3 4b0002c4 4b0002c3 4b0002c3 4b0002c1 4b0002c2 last-block pattern 4b0002c1 4b0002c1 4b0002c1 4b0002c1 4b0002c1 4b0002c1The same input now gives the same bits on every run.
Lab: contention, CAS and determinism 🔴
cd labs/m05/5.3 && nvcc -O2 -arch=native atomics.cu -o atomics && ./atomicsSources
Check your understanding
0 / 4 answered1.16 M threads each atomicAdd into one of K counters. Which K is fastest?
2.Why does the CAS-loop max run 13× slower on ascending input than on random input?
3.In the last-block pattern, what is the atomic used for?
4.What can go wrong if the __threadfence() is removed?