Histogram
What to do when thousands of threads want to increment the same counter — atomics, and the privatisation trick that rescues them.
- Why a plain increment is a race condition and what atomicAdd fixes
- How contention, not correctness, becomes the bottleneck
- How per-block privatisation cuts atomic traffic by orders of magnitude
Every kernel so far had threads writing to distinct locations. A histogram breaks that: thousands of threads classify their element and increment a shared counter, so collisions are not an edge case — they are the entire workload.
This program bins a million random letters into seven buckets.
Why result[bin]++ is wrong
That innocuous increment is really three operations: read the counter, add one, write it back. Two threads can read the same value before either writes, and one update is lost. With a million threads this is not a theoretical risk; counts come out wrong every run, and differently each time.
atomicAdd makes read-modify-write indivisible:
constexpr int BINS = 7;
constexpr int DIV = ((26 + BINS - 1) / BINS);
__global__ void histogram(char *a, int *result, int n) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int alpha_position;
for (int i = tid; i < n; i += (gridDim.x * blockDim.x)) {
alpha_position = a[i] - 'a'; // 'a' -> 0, 'b' -> 1, ...
atomicAdd(&result[alpha_position / DIV], 1);
}
}
Two details worth pausing on. DIV uses the same round-up idiom as the grid sizing in lesson 1, so 26 letters spread across 7 bins without the last bin overflowing. And the loop is a grid-stride loop: instead of one thread per element, each thread strides forward by the total number of threads in the grid. That decouples the launch configuration from the problem size, so the same kernel works for any n.
Correct, but now it is slow
The kernel is right and still performs badly, because all million increments land on just seven counters in global memory. The hardware serialises atomic operations to the same address, so those seven addresses become a queue that every thread waits in. More parallelism makes it worse, not better.
Privatisation
The fix is to give each block its own private copy of the histogram in shared memory. Threads contend only with the other threads in their block — hundreds rather than a million — and each block performs just BINS global atomics at the end.
__global__ void histogram(char *a, int *result, int n) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
// One private histogram per thread block
__shared__ int s_result[BINS];
// Threads 0..BINS-1 clear it; shared memory is not zero-initialised
if (threadIdx.x < BINS) {
s_result[threadIdx.x] = 0;
}
__syncthreads();
int alpha_position;
for (int i = tid; i < n; i += (gridDim.x * blockDim.x)) {
alpha_position = a[i] - 'a';
atomicAdd(&s_result[(alpha_position / DIV)], 1); // fast, shared-memory atomic
}
__syncthreads();
// Merge this block's private result into the global one
if (threadIdx.x < BINS) {
atomicAdd(&result[threadIdx.x], s_result[threadIdx.x]);
}
}
The two __syncthreads() calls bracket the work for the same reasons as in the reduction lesson: the first guarantees the histogram is zeroed before anyone increments it, the second guarantees every thread has finished counting before the merge reads it.
The arithmetic is worth doing. With 512 threads per block and \(2^{20}\) elements, the naive kernel issues about a million global atomics. The privatised version issues a million shared-memory atomics — far cheaper, and spread across blocks — plus only BINS global atomics per block. Atomics on shared memory are still serialised on collision, but they are an order of magnitude faster than global ones, and contention is divided among the blocks.
Note that atomicAdd is used even for the final merge. Blocks finish at unpredictable times, so that write is itself a race.
Checking the output
Both versions dump their bins to a .dat file for gnuplot:
cd cuda_from_scratch/05histogram
nvcc -o hist_global 01_global_atomic.cu && ./hist_global
nvcc -o hist_shared 02_shmem_atomic.cu && ./hist_shared
diff global_mem_histogram.dat shmem_histogram.dat && echo "identical"
Both use srand(1), so the input is the same every run and the two files must match exactly. If they differ, a synchronisation step is missing.
Try it yourself. Replace atomicAdd with a plain ++ in the naive kernel and run it several times — watch the totals disagree between runs, then confirm they no longer sum to \(2^{20}\). Afterwards, raise BINS to 26 (one bin per letter) and see how the gap between the two versions changes as contention drops.