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.

OpenCL memory model

Clear, exam-focused notes on the OpenCL memory model: address spaces, visibility, ordering, fences/barriers, host–device interaction, common pitfalls and sample model answers.

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

OpenCL programs run many threads (called work-items) in parallel on a device. The OpenCL memory model tells the programmer how data is placed, how and when one work-item can see another work-item's writes, and what synchronization (barriers, fences, atomics) is needed to make parallel code correct and reproducible. Engineers use this when writing kernels, debugging race conditions, and optimising memory access for GPUs and other accelerators.

Key ideas

Start from simple definitions (plain English) and then build the formal rules.

  • Kernel — a function that runs on the device; many copies execute in parallel. Define before use: kernel is invoked from the host; each executing copy is a work-item.
  • Work-item — a single instance of a kernel executing on the device. Each work-item has a unique ID in local and global index spaces.
  • Work-group — a group of work-items that can synchronise with each other and share local memory. A work-group maps to a hardware scheduling unit (compute unit) in many devices.
  • Address spaces — places where data lives. OpenCL defines (at least) these address spaces: __private, __local, __global, __constant. Define each before use:
    • __private: private to one work-item (like a CPU thread stack). Not visible to other work-items.
    • __local: shared by all work-items in a work-group. Fast, limited size; useful for tiling and exchange within a group.
    • __global: visible to all work-items on the device and accessible from the host via buffer objects.
    • __constant: read-only region in global device memory, optimized for broadcast reads.
  • Host memory vs device memory — the host (CPU) and device (GPU/accelerator) each manage memory objects; unless using shared virtual memory (SVM), buffers are explicitly transferred between host and device. Define SVM: Shared Virtual Memory (SVM) (OpenCL 2.0 feature) lets host and device share pointer-based access and avoids explicit copies for supported hardware/drivers. SVM comes in coarse-grain and fine-grain forms: coarse-grain buffer SVM requires explicit clEnqueueSVMMap/clEnqueueSVMUnmap around host accesses; fine-grain (buffer or system) SVM allows concurrent host/device access coordinated with atomics and fences (memory orders/scopes).

Memory visibility and ordering rules (concise, exam-style):

  1. Work-items in different work-groups have no implicit ordering or visibility for writes to __global or __local memory. Without explicit synchronisation, a read of a location modified by another work-item may see an old value or a value in-progress — resulting in a data race and undefined behaviour for conflicting non-atomic accesses. Note: __local memory is per-work-group; work-items in different work-groups never share the same __local storage.
  2. Within a work-group, a call to barrier(flags) synchronises work-items in that work-group. If the flags include CLK_LOCAL_MEM_FENCE or CLK_GLOBAL_MEM_FENCE, then memory writes performed by work-items before the barrier are guaranteed to be visible to work-items after the barrier (subject to the fence flags chosen). State this as a precise rule used in exams. All work-items in the work-group must execute this barrier, and they must pass the same flags; placing a barrier in divergent control flow where some work-items skip it results in undefined behavior (typically deadlock).
  3. Memory fences (mem_fence(flags)) provide ordering for memory operations but do not act as a control-synchronisation point between work-items; barrier is needed to synchronise threads in a group.
  4. Atomics: atomic operations (the atomic built-ins) provide read-modify-write semantics that avoid data races when multiple work-items update the same location. Use atomics to ensure race-free concurrent updates to shared integers or pointers. To make non-atomic writes visible to other work-items in a defined order, pair atomics with an appropriate fence (e.g., mem_fence in OpenCL 1.x or atomic_work_item_fence/work_group_barrier with suitable memory orders/scopes in OpenCL 2.0).

Assumptions and common exam derivations to show:

  • Assumption: Example assumes a kernel launched with multiple work-groups and work-items per group. Show step-by-step how a write in work-item A becomes visible to work-item B only after both (a) the writing work-item executes a write, (b) both reach a barrier with appropriate fence flags, and (c) the reading work-item executes after the barrier.
  • Derivation universities ask for: prove that without a barrier two work-items in the same group can still observe stale values because the compiler or hardware may reorder memory instructions for performance. So show a sequence of ordered operations and a reordering counter-example.

What to draw on the exam paper (diagram):

  • Draw one large rectangle labelled DEVICE. Inside it draw three boxes: GLOBAL MEMORY, COMPUTE UNIT 0, COMPUTE UNIT 1. Inside each compute unit draw two work-group boxes. Inside one work-group box show 4 small circles (work-items) and a shared small rectangle labelled __local memory. Draw arrows: work-items -> __local (reads/writes), global memory arrows to compute units. Label an arrow between host and global memory: clEnqueueWriteBuffer / clEnqueueReadBuffer (for non-SVM flows). This diagram should be annotated to show which regions are visible to which entities.

Formulas

For a programming/topic memory model, list the syntax and small API lines to remember (each on its own line): __private, __local, __global, __constant — OpenCL C address-space qualifiers; use before variable declarations. barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE) — synchronise work-items in a work-group and enforce memory visibility for local/global writes before the barrier. mem_fence(CLK_LOCAL_MEM_FENCE) — ensure ordering of memory accesses to __local memory inside a work-item (no cross-work-item synchronisation by itself). atomic_add(&x, value) — example atomic built-in (use atomics to avoid races when updating shared integer locations). (Exact names of atomic built-ins can vary with OpenCL version; check your OpenCL version doc.) clEnqueueWriteBuffer, clEnqueueReadBuffer, clEnqueueMapBuffer — host-side commands to transfer or map buffer objects between host and device (for non-SVM systems). clFinish — blocks until all previously enqueued commands in the command queue complete; clFlush — issues queued commands to the device but does not wait for their completion. Use in-order command queues or explicit event wait lists to order host/device operations, and use clFinish (or wait on events) when you must ensure completion before accessing data on the host.

Worked examples

  1. Model answer: Explain why this kernel has a race and how to fix it. Question: Two work-items in the same work-group run:
  • work-item 0: writes shared[0] = 1; then reads r = shared[1];
  • work-item 1: writes shared[1] = 2; then reads s = shared[0]; Both use __local int shared[2];. Answer (step-by-step):
  1. Define the problem: Both work-items perform writes and reads to the same __local array without synchronisation. The reads may see old values because hardware/compilers may reorder writes and reads; hence data race.
  2. Show the correct sequence with barrier: insert barrier(CLK_LOCAL_MEM_FENCE); after both writes and before both reads.
  3. Explain semantics: barrier ensures all work-items in the group reach the barrier; the local-mem fence ensures writes to __local are visible to other work-items after the barrier.
  4. Conclude: With the barrier, r will see 2 and s will see 1 (assuming both writes complete before the barrier and no further reorderings). Without it, behaviour is undefined.
  1. Model answer: Host–device memory visibility (short essay expected in exams) Question: Explain when a host-side write to a buffer becomes visible to kernels and when a kernel write becomes visible to host. Answer (concise):
  • For non-SVM: host writes become visible to kernels once the host enqueues a blocking write (clEnqueueWriteBuffer with blocking flag) or enqueues the write and subsequently calls clFinish on that command queue before kernel launch. Similarly, kernel writes to a buffer become visible to the host after the kernel finishes (the queue is finished) and the host reads the buffer via clEnqueueReadBuffer or clEnqueueMapBuffer followed by clFinish as needed.
  • For SVM (OpenCL 2.0+): the programmer may use fences and memory-ordering features to share pointers; exact semantics depend on the SVM granularity and implementation. (Hardware/driver support required.)
  1. Short kernel snippet showing correct use of __local and barrier (one small kernel only):
__kernel void tile_example(__global const float* A, __global float* B, int N) {
  __local float tile[64];
  int gid = get_global_id(0);
  int lid = get_local_id(0);
  // load into local
  tile[lid] = A[gid];
  barrier(CLK_LOCAL_MEM_FENCE);
  // safe to read tile[] now
  B[gid] = tile[(lid+1)%get_local_size(0)];
}

Explain: the barrier ensures the local writes are visible to all work-items before reading tile, and assume the work-group size is 64 so that tile[64] is large enough; otherwise pass __local memory as a kernel argument sized by the host to avoid out-of-bounds access.

Common mistakes

  • Using non-atomic updates on a shared counter in __global across multiple work-groups — this is a race and undefined.
  • Confusing host-side memory visibility: assuming a kernel's writes are visible on the host immediately after kernel enqueue (instead of after kernel completion / clFinish / explicit read or map).
  • Forgetting address-space qualifiers for pointers passed into kernels; e.g., declaring a pointer without __global is a compile error in OpenCL C 1.x (OpenCL 2.0 introduces a generic address space in limited contexts).

For your exam

Kinds of questions that appear and what a full-marks answer includes:

  • Definitions: define address spaces (__private, __local, __global, __constant) and SVM. Include visibility and lifetime for each.
  • Short notes: Describe barrier vs mem_fence. A full answer states where each synchronises/orders, expected flags, and examples.
  • Derivations / proofs: Show a memory-reordering counter-example and demonstrate why a barrier is needed. Draw a timeline figure of operations across two work-items and indicate reordering.
  • Programs / code snippets: Small kernel that uses __local and barrier correctly. Include explanation of why it is correct.
  • Diagrams: Draw host, device, global memory, compute units, work-groups, and show buffer transfers.

Quick check

  1. Which address space is private to a work-item?
  2. Does mem_fence(CLK_LOCAL_MEM_FENCE) synchronise multiple work-items by itself?
  3. What host command sequence ensures a buffer written by a kernel is safely read by the host? Answers: 1) __private. 2) No; use barrier to synchronise work-items (mem_fence only orders accesses). 3) Ensure kernel completes (clFinish or wait on queue), then clEnqueueReadBuffer or clEnqueueMapBuffer (and finish if non-blocking).

Notes for the reviewer: I aimed to keep statements precise but short. I marked some API/atomic names broadly where OpenCL version differences matter and indicated where the student should check the version-specific details.

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

Stuck on something here?