Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Synchronisation and parallel programming issues

Practical study notes on synchronization in GPU parallel programming: definitions, laws, CUDA synchronization primitives, common bugs, worked CUDA examples (atomic and block reduction), exam guidance and quick checks.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Key ideas

(Definitions are bolded where first used.)

  • Thread: a single sequential execution context on the GPU. Threads execute the kernel code.

  • Block: a group of threads that can communicate via shared memory and use block-level barriers. In CUDA, blocks are organized into a grid.

  • Grid: all blocks launched for a kernel.

  • Synchronisation: the actions a programmer takes to control the relative ordering of operations from multiple threads so the result is correct. This includes barriers and ordering operations.

  • Race condition: a situation where the final result depends on the relative timing of two or more concurrent accesses to the same memory location, at least one being a write. Exam-style statement: "A race exists if two threads concurrently access the same memory location and at least one access is a write and there is no ordering/synchronisation enforcing a defined order."

  • Critical section: a code region that accesses shared resources and must not be executed concurrently by multiple threads to preserve correctness.

  • Atomic operation: an operation that appears to execute as a single indivisible step from the point of view of other threads. It prevents races on that operation (e.g., atomicAdd). Atomics do not automatically order other non-atomic accesses unless combined with memory fences.

  • Barrier: a point where threads wait until a set of threads reach the same barrier point; after passing, all have reached the barrier. In CUDA per-block barrier is __syncthreads(); there is no general built-in global barrier across blocks inside a kernel, except via Cooperative Groups grid-wide synchronization (e.g., cg::this_grid().sync()) when using a cooperative launch on supported GPUs.

  • Deadlock: a state where threads wait forever because each waits for the other to do something. For GPUs, a common case is incorrect use of locks when thread scheduling prevents lock holders from running.

  • Livelock: threads keep changing state in response to others but no progress is made.

  • Starvation: some thread(s) never get resources/time to progress.

  • Memory consistency model: the rules determining when writes by one thread become visible to reads by another. Sequential consistency is the strongest simple model: results are as if operations of all threads were interleaved in some global order consistent with each thread's program order. GPUs do not guarantee full sequential consistency for performance reasons.

  • Happens-before relation: a partial order between operations capturing synchronisation: if A happens-before B then effects of A are visible to B. Barriers, atomics with appropriate fences, and kernel launch/complete events create happens-before edges.

  • CUDA-specific primitives and behaviour (assumptions):

    • __syncthreads() is a block-level barrier: all threads in the block must reach it; it synchronises both control flow and memory visibility at block scope (shared and global memory) among threads of that block. Placing __syncthreads() in divergent control flow where some threads do not reach it can cause deadlock/undefined behavior.
    • __syncwarp() is a warp-level barrier (synchronises threads in same warp) — useful for warp-synchronous algorithms; caution: rely only on it with warp-uniform control flow.
    • atomicXxx() functions perform atomic read-modify-write on a memory location. There are atomics for int and float (float atomicAdd on modern GPUs), for 32-bit and 64-bit where supported.
    • __threadfence_block(), __threadfence(), and __threadfence_system() are memory fences with different visibility domains: block-only, device-wide, and system (host-visible), respectively.
  • Important constraints and common exam points:

    • There is no general safe way to synchronise across blocks inside one kernel; the usual pattern is to finish the kernel, synchronize on the host (or rely on same-stream ordering), then launch another kernel. An exception is Cooperative Groups grid-wide synchronization, which is available only for cooperative launches on supported hardware and within its constraints.
    • Using locks on GPU is dangerous: GPU scheduling does not guarantee forward progress across blocks; waiting blocks can occupy all SM resources and prevent the block that would release a lock from running, causing deadlock—avoid inter-block locks and long critical sections; prefer lock-free or per-block aggregation patterns.
  • Step-by-step typical derivation (exam style): Why __syncthreads() is required when using shared memory for reduction.

    1. Threads load per-thread values into shared memory slots.
    2. Reduction code reads other threads' shared slots. Without ordering, a thread might read a slot that another thread has not yet written → race.
    3. Insert __syncthreads() after writes: this enforces that all thread writes to shared memory are visible to all threads after the barrier (happens-before established).
    4. Therefore reductions read correct values.
  • Diagram to draw when asked: draw a grid with two blocks; within a block show 4 threads, arrows from each thread to a shared-memory array slot they wrote, label a barrier __syncthreads() as a vertical bar and explain that no thread passes until all reach the bar.

Formulas

(For programming/synchronisation, these are the key syntax lines to remember.) __syncthreads() — Block-level barrier. Use inside a kernel. No arguments. __syncwarp() — Warp-level synchronisation. Optionally with mask on modern toolchains. atomicAdd(&var, val) — Atomic add on integer (and float where supported). Arguments: pointer, value. Returns the previous value. __threadfence_block() — Ensure memory writes by the calling thread are visible to threads in the same block. __threadfence() — Ensure memory writes by the calling thread are visible to all threads on the device. __threadfence_system() — Ensure memory writes are visible to the host and other devices (system scope). Note: Fences only order visibility (they do not block other threads). cudaDeviceSynchronize() — Host call that blocks until device has completed preceding tasks (used to order kernels on host). Kernels launched in the same stream are ordered without explicit synchronization; for cross-stream ordering, use events (cudaEventRecord/cudaEventSynchronize or cudaStreamWaitEvent).

Explain symbols and when: each is a function name in CUDA C++ and applies as described above. Units: none (programming syntax).

Worked examples

Example 1 — Correct parallel sum using per-thread atomics (deterministic):

// File: sum_atomic.cu
#include <cstdio>
#include <cuda_runtime.h>

__global__ void sum_atomic_kernel(const int *a, int n, int *result) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {
        // each thread adds its element atomically
        atomicAdd(result, a[idx]);
    }
}

int main() {
    const int N = 1024;
    int *h_a = new int[N];
    for (int i = 0; i < N; ++i) h_a[i] = 1; // sum should be 1024

    int *d_a; int *d_sum; int h_sum = 0;
    cudaMalloc(&d_a, N * sizeof(int));
    cudaMalloc(&d_sum, sizeof(int));
    cudaMemcpy(d_a, h_a, N * sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_sum, &h_sum, sizeof(int), cudaMemcpyHostToDevice);

    int threads = 256;
    int blocks = (N + threads - 1) / threads;
    sum_atomic_kernel<<<blocks, threads>>>(d_a, N, d_sum);
    cudaDeviceSynchronize();

    cudaMemcpy(&h_sum, d_sum, sizeof(int), cudaMemcpyDeviceToHost);
    printf("Sum = %d\n", h_sum);

    cudaFree(d_a); cudaFree(d_sum); delete[] h_a;
    return 0;
}

Sample input: none (array built-in N=1024, all ones). Exact output: Sum = 1024

Example 2 — Block-wise reduction with shared memory and one atomic per block (uses __syncthreads()):

// File: sum_block_reduce.cu
#include <cstdio>
#include <cuda_runtime.h>

__global__ void sum_block_kernel(const int *a, int n, int *result) {
    extern __shared__ int sdata[]; // shared memory per block
    int tid = threadIdx.x;
    int idx = blockIdx.x * blockDim.x + tid;

    // load input into shared memory
    int x = (idx < n) ? a[idx] : 0;
    sdata[tid] = x;
    __syncthreads(); // ensure all stores to sdata are visible

    // reduce in shared memory
    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (tid < s) sdata[tid] += sdata[tid + s];
        __syncthreads();
    }

    // thread 0 in block adds block sum to global result
    if (tid == 0) atomicAdd(result, sdata[0]);
}

int main() {
    const int N = 1024;
    int *h_a = new int[N];
    for (int i = 0; i < N; ++i) h_a[i] = 1;

    int *d_a; int *d_sum; int h_sum = 0;
    cudaMalloc(&d_a, N * sizeof(int));
    cudaMalloc(&d_sum, sizeof(int));
    cudaMemcpy(d_a, h_a, N * sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_sum, &h_sum, sizeof(int), cudaMemcpyHostToDevice);

    int threads = 256;
    int blocks = (N + threads - 1) / threads;
    sum_block_kernel<<<blocks, threads, threads * sizeof(int)>>>(d_a, N, d_sum);
    cudaDeviceSynchronize();

    cudaMemcpy(&h_sum, d_sum, sizeof(int), cudaMemcpyDeviceToHost);
    printf("Sum = %d\n", h_sum);

    cudaFree(d_a); cudaFree(d_sum); delete[] h_a;
    return 0;
}

Sample input: none (array built-in N=1024, all ones). Exact output: Sum = 1024

Notes: these programs are intentionally simple to show deterministic correct summation using atomics and block synchronisation. In real code you must check return codes and consider 64-bit sums for large N. For the shared-memory reduction shown, assume blockDim.x is a power of two; otherwise adjust the reduction loop to handle trailing elements.

Common mistakes

  • Using atomics on unsupported types or assuming atomicAdd(float) exists on all GPUs — check architecture and CUDA version.
  • Holding locks or busy-waiting in kernels for long times → can cause deadlock or poor performance because of SM scheduling.
  • Assuming warp-level functions (__syncwarp) synchronise all threads in a block — they only apply to threads in the same warp.
  • Mixing host and device memory ordering without __threadfence_system() when communicating with host.
  • Relying on sequential consistency: modern GPUs may reorder memory operations for performance; use fences and atomics to establish happens-before.

For your exam

Kinds of questions and what full-marks answers include:

  • Definitions: give the precise definition and an example (e.g., race condition: show two threads write/read same location). Always bold the term and state conditions.
  • Short notes: describe __syncthreads(), atomics, fences — include purpose, scope (block/device/system), and a short code example or pseudo-code.
  • Derivations/explanations: step-by-step why __syncthreads() is necessary for shared-memory reduction; draw the diagram described above.
  • Programs: write a small CUDA kernel that uses shared memory and a barrier; include host code to allocate, copy, launch and retrieve results. Explain why the result is correct.
  • Diagrams: draw threads -> shared array -> barrier -> reduction steps. Label thread indices, shared slots, barrier.
  • Practical/essay: discuss deadlock sources on GPU and strategies to avoid (use lock-free algorithms, short critical sections, per-block aggregation then combine on host).

Full-marks answers must explicitly state assumptions (e.g., number of threads per block, visibility scopes), show synchronization points, and justify why they prevent races using the happens-before argument.

Quick check

  1. What does __syncthreads() do and what is its scope?
  2. Give the condition that defines a race condition.
  3. Name two CUDA primitives that create a happens-before relation between threads.

Answers: 1) It is a block-level barrier that waits for all threads in the block and synchronises shared-memory reads/writes. 2) Two concurrent accesses to the same memory location with at least one write and no ordering/synchronisation. 3) __syncthreads() and atomics (e.g., atomicAdd); also __threadfence() and kernel launch/complete.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?