The OpenCL standard and kernels
Clear, exam-focused notes on the OpenCL standard and kernels: what OpenCL is, its execution model, API call sequence, kernel writing rules, memory qualifiers and common pitfalls, with two worked examples (vector add host+kernel and a reduction kernel).
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 is a portable open standard to run compute on heterogeneous devices (CPUs, GPUs, FPGAs). Engineers use OpenCL when they must write a single program that can execute on different vendor devices, control device memory and parallel execution precisely, or integrate GPU acceleration without vendor‑specific APIs like CUDA.
Key ideas
Device: a compute device that contains one or more Compute Units (CUs) (for example a GPU device or CPU device). Use clGetDeviceIDs to enumerate devices on a platform.
Context: an object that groups one or more devices and manages memory objects and programs shared between them. Created with clCreateContext.
Command queue: an object to submit commands (memory transfer, kernel launches) to a device. Created with clCreateCommandQueue (OpenCL 1.x) or clCreateCommandQueueWithProperties (OpenCL 2.0+). Queues are in-order by default; out-of-order execution can be enabled via the flag CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (as a property bit in OpenCL 1.x, or via properties to clCreateCommandQueueWithProperties in OpenCL 2.0+).
Program: the compiled object created from kernel source or binary. Create with clCreateProgramWithSource and compile with clBuildProgram.
Kernel: a function written in OpenCL C and marked with the keyword __kernel (or
kernelin newer syntax). It runs on the device for many parallel work‑items.Work‑item: the smallest unit of execution that runs a kernel instance. Each work‑item has an index accessible with get_global_id(dim) and get_local_id(dim).
NDRange: the N‑dimensional index space (1D, 2D or 3D) of work‑items launched for a kernel. The NDRange has a global size and optionally a local (work‑group) size.
Work‑group: a set of work‑items that can share local memory and synchronize with barrier. The size of a work‑group is the local size in each dimension.
Memory address spaces / qualifiers (OpenCL C):
- __global: memory accessible by all work‑items and the host. Usually mapped to device global memory (DRAM).
- __local: memory shared inside a work‑group (fast on GPU; similar to shared memory in CUDA).
- __constant: read‑only global memory (can be cached specially).
- __private: per‑work‑item private memory (registers or stack).
Always put the qualifier when the argument is a buffer pointer: e.g.,
__global float* a.Kernel arguments: set from host using clSetKernelArg in the host API. For local memory, pass
NULLwith size to clSetKernelArg to allocate per work‑group local scratch.Synchronization in kernels: the function barrier(flags) synchronizes all work‑items in the same work‑group.
flagsis one ofCLK_LOCAL_MEM_FENCE,CLK_GLOBAL_MEM_FENCEor both, to ensure memory visibility. All work‑items in the work‑group must reach each barrier; placing a barrier inside divergent control flow is undefined and can deadlock.Host–device interaction and data movement: memory objects (buffers or images) are created in a context (accessible by all devices in the context) using clCreateBuffer or clCreateImage. Data is transferred with clEnqueueWriteBuffer and clEnqueueReadBuffer or mapped with clEnqueueMapBuffer and unmapped with clEnqueueUnmapMemObject.
Execution sequence (typical): query platform/device → create context → create command queue → create program from source → build program → create kernel → create buffers → set kernel args → enqueue write buffer(s) → enqueue NDRange kernel → enqueue read buffer(s) → release resources.
Error handling: most OpenCL calls return an error code. Always check the returned code and, after clBuildProgram, if build failed retrieve the build log with clGetProgramBuildInfo.
Diagram (draw in exam):
- Draw a rectangle labeled Host (left) and a rectangle labeled Device (right).
- Inside Device draw boxes: Compute Units (CUs), each CU contains several Processing Elements (PEs). Above device draw memory blocks labeled Global Memory and Local Memory inside each CU.
- Draw arrows: Host → Command Queue → Kernel launch → NDRange of work‑items inside Device. Label a small square inside NDRange as a work‑item with labels get_global_id(0) and get_local_id(0). Show a work‑group as a contiguous block of work‑items.
Mapping indices: to map a 2D array to NDRange, use
i = get_global_id(0); j = get_global_id(1);and index asA[j*width + i]when row-major. Always state row-major storage assumption in answers.
Assumptions often required: OpenCL C is C99‑based but with restrictions (no recursion, limited standard library, no malloc/free in kernels). OpenCL version differences: API functions for command queue creation changed in 2.0; when writing exam answers state which OpenCL version you assume (1.2 is common in university questions).
Formulas
For a programming topic, the syntax and call sequence to remember (each on its own line):
cl_int clGetPlatformIDs(cl_uint, cl_platform_id*, cl_uint*) — get platform IDs.
cl_int clGetDeviceIDs(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*) — get devices.
cl_context clCreateContext(cl_context_properties*, cl_uint, cl_device_id*, void (CL_CALLBACK*)(...), void*, cl_int*) — create context.
cl_command_queue clCreateCommandQueueWithProperties(cl_context, cl_device_id, const cl_queue_properties*, cl_int*) — create command queue (OpenCL 2.0+).
cl_command_queue clCreateCommandQueue(cl_context, cl_device_id, cl_command_queue_properties, cl_int*) — create command queue (OpenCL 1.x).
cl_program clCreateProgramWithSource(cl_context, cl_uint, const char**, const size_t*, cl_int*) — create program from source.
cl_int clBuildProgram(cl_program, cl_uint, const cl_device_id*, const char*, void (*pfn_notify)(...), void*) — build program; check build log on errors.
cl_kernel clCreateKernel(cl_program, const char* kernel_name, cl_int*) — create kernel object.
cl_mem clCreateBuffer(cl_context, cl_mem_flags, size_t, void*, cl_int*) — allocate buffer on device.
cl_int clSetKernelArg(cl_kernel, cl_uint arg_index, size_t arg_size, const void* arg_value) — set kernel argument.
cl_int clEnqueueWriteBuffer(cl_command_queue, cl_mem, cl_bool blocking_write, size_t offset, size_t size, const void* ptr, cl_uint, const cl_event*, cl_event*) — write host→device.
cl_int clEnqueueNDRangeKernel(cl_command_queue, cl_kernel, cl_uint work_dim, const size_t* global_work_offset, const size_t* global_work_size, const size_t* local_work_size, cl_uint, const cl_event*, cl_event*) — launch kernel.
cl_int clEnqueueReadBuffer(cl_command_queue, cl_mem, cl_bool blocking_read, size_t offset, size_t size, void* ptr, cl_uint, const cl_event*, cl_event*) — read device→host.
clFinish(cl_command_queue) — wait until all queued commands finish.
Worked examples
Example 1 — Complete host + kernel: vector addition (OpenCL 1.2 C host). This compiles on a system with OpenCL headers and library. The kernel string is embedded.
Host code (compile with: gcc vec_add.c -lOpenCL -o vec_add):
// vec_add.c -- minimal OpenCL 1.2 host program
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
const char* src =
"__kernel void vecadd(__global const float* a, __global const float* b, __global float* c) {\n"
" size_t gid = get_global_id(0);\n"
" c[gid] = a[gid] + b[gid];\n"
"}\n";
int main(){
const int N = 8;
float A[N], B[N], C[N];
for(int i=0;i<N;i++){ A[i]=i; B[i]=10+i; }
cl_int err;
cl_uint numPlatforms;
err = clGetPlatformIDs(0, NULL, &numPlatforms);
cl_platform_id* plats = malloc(sizeof(cl_platform_id)*numPlatforms);
clGetPlatformIDs(numPlatforms, plats, NULL);
cl_device_id device;
clGetDeviceIDs(plats[0], CL_DEVICE_TYPE_GPU, 1, &device, NULL);
cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
cl_command_queue queue = clCreateCommandQueue(context, device, 0, &err);
cl_program program = clCreateProgramWithSource(context, 1, &src, NULL, &err);
err = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
cl_kernel kernel = clCreateKernel(program, "vecadd", &err);
cl_mem bufA = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*N, NULL, &err);
cl_mem bufB = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*N, NULL, &err);
cl_mem bufC = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float)*N, NULL, &err);
clEnqueueWriteBuffer(queue, bufA, CL_TRUE, 0, sizeof(float)*N, A, 0, NULL, NULL);
clEnqueueWriteBuffer(queue, bufB, CL_TRUE, 0, sizeof(float)*N, B, 0, NULL, NULL);
clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufA);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &bufB);
clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufC);
size_t global = N;
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, NULL, 0, NULL, NULL);
clFinish(queue);
clEnqueueReadBuffer(queue, bufC, CL_TRUE, 0, sizeof(float)*N, C, 0, NULL, NULL);
printf("Result: ");
for(int i=0;i<N;i++) printf("%g ", C[i]);
printf("\n");
clReleaseMemObject(bufA); clReleaseMemObject(bufB); clReleaseMemObject(bufC);
clReleaseKernel(kernel); clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context);
free(plats);
return 0;
}
Sample input: none (program uses built-in arrays). Exact output (stdout):
Result: 10 12 14 16 18 20 22 24
So final answer displayed is: Result: 10 12 14 16 18 20 22 24
Example 2 — Kernel for parallel reduction (sum) inside one work‑group. This is a typical exam model answer to show local memory and barrier usage.
Kernel (OpenCL C):
__kernel void reduce_sum(__global const float* in, __global float* out, __local float* sdata) {
size_t lid = get_local_id(0);
size_t gid = get_global_id(0);
sdata[lid] = in[gid];
barrier(CLK_LOCAL_MEM_FENCE);
for(size_t stride = get_local_size(0)/2; stride>0; stride >>= 1) {
if(lid < stride) sdata[lid] += sdata[lid + stride];
barrier(CLK_LOCAL_MEM_FENCE);
}
if(lid == 0) out[get_group_id(0)] = sdata[0];
}
Host notes: launch with global size = multiple of local size; set local size (e.g., 256) and pass local buffer by clSetKernelArg(kernel, 2, sizeof(float)*local_size, NULL);. Then perform final host sum over group results if there are multiple groups. Ensure the local size is a power of two for this loop structure, or handle any leftover elements explicitly; also ensure the global size matches the data length or include bounds checks.
This answers the typical exam question: explain the reduction steps, why barriers are required after write and after each add, and how local memory reduces global memory traffic.
Common mistakes
- Not using the correct memory qualifier on a pointer argument (e.g., missing
__global), leading to undefined behaviour. - Assuming
get_global_id(0)runs from 0..N-1 without ensuring global size equals N; off‑by‑one when NDRange is larger than data length. - Forgetting to allocate local memory via
clSetKernelArg(..., size, NULL)for__localarguments. - Using
clCreateCommandQueueon systems where it is deprecated without noting OpenCL version differences. - Using blocking vs non‑blocking transfers incorrectly; forgetting to wait (e.g.,
clFinishor event waits) before using results when operations are non‑blocking.
For your exam
Kinds of questions:
- Definitions: explain OpenCL, work‑item, work‑group, NDRange, memory qualifiers, kernel, program.
- Short notes: host–device execution sequence, command queue, differences between
__localand__globalmemory. - Derivations / diagrams: draw device architecture, show mapping of NDRange to data indexes, derive index formulas for 2D arrays.
- Programs: write a kernel for vector add or reduction and outline the host steps to run it (API sequence). Full‑marks answers include kernel source, correct qualifiers, and the exact host call sequence with mention of sizes and synchronization.
- Debugging: explain where and why a build might fail; how to get and read the build log.
Always state assumptions (OpenCL version, row/column major order, device type) at the start of your answer.
Quick check
- Which OpenCL qualifier is used for memory shared within a work‑group?
- How do you obtain a kernel's global id inside an OpenCL kernel?
- Which API call compiles program source to a device binary?
Answers: __local; get_global_id(dim); clBuildProgram
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?