Atomics
When thousands of threads update the same counter, read-modify-write is a race. Atomics make the three steps indivisible. They also make contention visible.
The lost update#
This looks correct:
__global__ void count(int* total, const int* flags, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n && flags[i]) {
*total = *total + 1; // load, add, store — three steps
}
}Two threads can load the same old value, both add one, and both store the same new value. One increment disappears. With 32 threads per warp racing, the final count can be almost anything between 1 and 32.
The fix is a single hardware operation:
atomicAdd(total, 1);Every thread's increment is applied exactly once, no matter how many threads hit the address at the same time.
A histogram#
Counting how often each value appears is the classic atomic workload:
#include <cstdio>
#include <cuda_runtime.h>
constexpr int BINS = 8;
__global__ void histogram(const int* in, int* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
atomicAdd(&out[in[i]], 1);
}
}
int main() {
const int n = 32;
int *in, *out;
cudaMallocManaged(&in, n * sizeof(int));
cudaMallocManaged(&out, BINS * sizeof(int));
for (int i = 0; i < n; ++i) {
in[i] = i % BINS;
out[i % BINS] = 0;
}
histogram<<<1, n>>>(in, out, n);
cudaDeviceSynchronize();
for (int b = 0; b < BINS; ++b) printf("bin %d: %d\n", b, out[b]);
cudaFree(in); cudaFree(out);
return 0;
}bin 0: 4 bin 1: 4 bin 2: 4 bin 3: 4 bin 4: 4 bin 5: 4 bin 6: 4 bin 7: 4
Every thread reads one input value and atomically increments one bin. No lost updates.
Without the atomic, the output would be smaller and would change from run to run. Try it: replace atomicAdd with out[in[i]]++ and run the program several times.
Contention is the cost#
An atomic to a single address is serialised in hardware. If all 32 lanes of a warp add to the same bin, the warp takes 32 atomic operations' worth of time. If they hit 32 different bins, the operations proceed in parallel.
For a histogram with few bins, this is the bottleneck. Two standard fixes:
1. Privatise per block#
Give each block its own copy of the histogram in shared memory, then merge once at the end:
__global__ void histogramShared(const int* in, int* out, int n) {
__shared__ int local[BINS];
for (int b = threadIdx.x; b < BINS; b += blockDim.x) local[b] = 0;
__syncthreads();
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n;
i += blockDim.x * gridDim.x) {
atomicAdd(&local[in[i]], 1); // fast: shared memory
}
__syncthreads();
for (int b = threadIdx.x; b < BINS; b += blockDim.x) {
atomicAdd(&out[b], local[b]); // one global atomic per bin per block
}
}Global atomics drop from n to BINS × blocks. Shared atomics are also much cheaper than global ones, and they never leave the SM.
2. Use more bins#
If the data distribution is known, replicate the histogram (say, four copies, selected by threadIdx.x % 4) and sum the copies at the end. More bins spread the contention; the merge is cheap.
The atomic toolbox#
| Function | Supports | Notes |
|---|---|---|
atomicAdd | int, unsigned, float, double* | Double needs CC 6.0+ |
atomicSub | int, unsigned | |
atomicExch | int, unsigned, float | Swap |
atomicMin / atomicMax | int, unsigned, long long | No float version |
atomicInc / atomicDec | unsigned | Wraparound counters |
atomicCAS | int, unsigned, long long | Compare-and-swap; builds the rest |
atomicAnd / atomicOr / atomicXor | int, unsigned | Bit operations |
atomicAdd(double*) requires compute capability 6.0 or newer.
atomicCAS(address, compare, value) is the primitive behind custom atomics. It returns the old value and stores value only if the old value equals compare. A compare-and-swap loop can implement atomic max for floats, atomic multiply, or a lock:
__device__ float atomicMaxFloat(float* addr, float value) {
int* ai = reinterpret_cast<int*>(addr);
int old = *ai, assumed;
do {
assumed = old;
float f = __int_as_float(assumed);
if (f >= value) break;
old = atomicCAS(ai, assumed, __float_as_int(value));
} while (assumed != old);
return __int_as_float(old);
}This is a loop, so it can starve under heavy contention. Prefer reductions when you can.
Atomics do not order memory#
An atomic makes that address safe. It says nothing about the stores your thread made to other addresses. If you publish a data structure by setting a flag, the data must be visible before the flag:
data[0] = 42;
__threadfence(); // make the store visible to the grid
atomicExch(flag, 1); // then publishEven with the fence, the consumer can spin forever if the producing block is never scheduled. Cross-block producer/consumer is a design smell; use two kernels or cooperative groups.
Floating-point atomics are not associative#
atomicAdd(float*) is exact per operation, but the order of additions is arbitrary. Floating-point addition is not associative, so summing 10 million floats with atomics can give a slightly different result each run.
That is usually acceptable for a histogram or a counter, and not acceptable when you need reproducible results. For deterministic sums, use a tree reduction (next chapter) with a fixed order, or accumulate in double.
When to reach for atomics#
- A small number of updates to shared state (counters, flags, histograms).
- Irregular scatter where multiple threads may target the same location.
- Implementing locks or custom reductions.
Do not use them:
- As a substitute for a reduction. A tree reduction in shared memory is faster than
nglobal atomics. - To synchronise blocks. Atomics are not barriers.
- On every element of a large array when a per-thread or per-block accumulation would do.
Exercises#
- Run the histogram without atomics ten times. How much does the total vary? Does it ever equal 32?
- In
histogramShared, remove the second__syncthreads(). What can go wrong? - Change the input to
i % 2so every thread hits one of two bins. Measure both versions withcudaEvent. How large is the shared-memory win? - Implement
atomicMaxforfloatusingatomicCASand test it on an array of mixed positive and negative values. - Why does
atomicAddon adouble*require CC 6.0? What happens on older hardware?