What Is a GPU Kernel? Start Parallel Work with Threads, Blocks, and a Grid
A GPU kernel is a function that runs on a GPU so many threads can apply the same program to their own data. CPU host code launches it, and each thread uses its thread and block indices to choose the data it handles. This guide follows a CUDA C++ vector addition to explain the kernel’s role, launch configuration, bounds checks, and completion. Other GPU platforms and frameworks may use different APIs and execution details. [NVIDIA CUDA Programming Guide — Programming Model](https://docs.nvidia.com/cuda/cuda-programming-guide/01-introduction/programming-model.html)
What Is a GPU Kernel? Start Parallel Work with Threads, Blocks, and a Grid
A GPU kernel is a function that runs on a GPU so many threads can apply the same program to their own data. CPU host code launches it, and each thread uses its thread and block indices to choose the data it handles. This guide follows a CUDA C++ vector addition to explain the kernel’s role, launch configuration, bounds checks, and completion. Other GPU platforms and frameworks may use different APIs and execution details. NVIDIA CUDA Programming Guide — Programming Model
How is a GPU kernel different from an ordinary function?
A normal CPU function runs in the control flow of the CPU thread that called it. In CUDA, a function declared with __global__ is launched by CPU host code, but its body runs on the GPU across many CUDA threads. Think of a launch as submitting a group of threads that run the same calculation, rather than calling a function once to receive one result. NVIDIA CUDA Programming Guide — Intro to CUDA C++
| Aspect | CPU host code | CUDA GPU kernel |
|---|---|---|
| Where it runs | CPU and host memory | GPU device execution resources and accessible memory |
| How work is divided | The calling thread usually controls the function’s loop | Many threads in a launch run the same kernel code independently |
| How data is selected | Function arguments and CPU control flow select items | Each thread combines built-in indices to find its assigned item |
| Main role | Prepare work, manage memory and execution, handle results | Apply an operation in parallel to many data items |
A CUDA program normally starts on the CPU. Host code prepares data, launches a kernel on the device, and checks results when needed. Work is easier to distribute when the same computation applies independently to many data items. If the workload is tiny or data movement costs more than the computation, a GPU kernel is not guaranteed to make the whole task faster. NVIDIA CUDA Programming Guide — Programming Model
How do threads, blocks, and a grid divide the data?
A CUDA launch groups threads into blocks, then groups blocks into a grid. threadIdx identifies a thread within its block, while blockIdx identifies that block within the grid. For one-dimensional work, a thread’s linear index is:
i = blockIdx.x * blockDim.x + threadIdx.x
Here blockDim.x is the number of threads in one block. For example, with 256 threads per block, block 2 handles indices 512 through 767. The launch configuration sets the block and grid sizes. Blocks are not guaranteed to run in a particular order, so a basic kernel must not assume that one block can immediately read another block’s result or synchronize with it. NVIDIA CUDA Programming Guide — Programming Model
| CUDA value | What it identifies | Use in this example |
|---|---|---|
threadIdx.x | Thread position inside its block | Adds the thread’s offset within the block |
blockIdx.x | Block position in the grid | Adds the offset contributed by earlier blocks |
blockDim.x | Threads in one block | Scales the block index to a data offset |
gridDim.x | Blocks in the grid | Describes how many blocks were launched |
The one-dimensional mapping can be pictured like this. The last block may have threads whose computed index is beyond the data length.
CPU host: prepare inputs and launch the kernel
└─ grid: multiple thread blocks
├─ block 0: threads 0…255 → elements 0…255
├─ block 1: threads 0…255 → elements 256…511
└─ last block: only in-range threads handle remaining elements
Each thread's linear position i = blockIdx.x × blockDim.x + threadIdx.xRound the grid size up by dividing the number of required threads by the threads per block. Some threads in the final block may therefore be extra. The kernel checks i < n so those threads do not access outside the arrays. Keeping this check is a simple safe pattern even when the length happens to be an exact multiple of the block size. NVIDIA CUDA Programming Guide — Intro to CUDA C++
How do you run a vector-add kernel end to end?
The example below adds two inputs and stores the result in an output array. cudaMallocManaged creates buffers accessible to both the host and GPU, so the example omits explicit copy calls. Unified Memory is managed by the NVIDIA driver, but its placement and performance can vary by system. The length 1003 is not a multiple of 256, which also exercises the final block’s bounds check. NVIDIA CUDA Programming Guide — Unified Memory and Kernel Launch
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#define CUDA_CHECK(call) do { \
cudaError_t err = (call); \
if (err != cudaSuccess) { \
std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, cudaGetErrorString(err)); \
std::exit(EXIT_FAILURE); \
} \
} while (0)
__global__ void add(const float* a, const float* b, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
out[i] = a[i] + b[i];
}
}
int main() {
constexpr int n = 1003;
constexpr int threads = 256;
const int blocks = (n + threads - 1) / threads;
float *a = nullptr, *b = nullptr, *out = nullptr;
CUDA_CHECK(cudaMallocManaged(&a, n * sizeof(float)));
CUDA_CHECK(cudaMallocManaged(&b, n * sizeof(float)));
CUDA_CHECK(cudaMallocManaged(&out, n * sizeof(float)));
for (int i = 0; i < n; ++i) {
a[i] = static_cast<float>(i);
b[i] = 2.0f * static_cast<float>(i);
}
add<<<blocks, threads>>>(a, b, out, n);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaDeviceSynchronize());
bool correct = true;
for (int i = 0; i < n; ++i) {
const float expected = 3.0f * static_cast<float>(i);
if (std::fabs(out[i] - expected) > 1e-5f) {
std::fprintf(stderr, "Mismatch at %d: got %f, expected %f\n", i, out[i], expected);
correct = false;
break;
}
}
CUDA_CHECK(cudaFree(a));
CUDA_CHECK(cudaFree(b));
CUDA_CHECK(cudaFree(out));
if (!correct) return EXIT_FAILURE;
std::printf("GPU and CPU results match (n=%d)\n", n);
return EXIT_SUCCESS;
}blocks uses ceiling division: (n + threads - 1) / threads. A kernel launch is asynchronous relative to the CPU, so host code may continue before GPU work finishes. The example checks launch errors with cudaGetLastError() and waits with cudaDeviceSynchronize(), which also reports execution errors. Larger applications with multiple streams may use narrower stream or event synchronization. NVIDIA CUDA Programming Guide — Launch and Synchronization
How do you check the result and decide whether a kernel fits?
Prerequisites: An NVIDIA GPU and operating system supported by CUDA, a compatible NVIDIA driver and CUDA Toolkit, and nvcc. The CUDA 13.5 Quick Start Guide provides platform-specific installation and basic run checks. Driver packaging and installation vary by operating system and Toolkit version, so use the current guide for your system. This sample uses the CUDA C++ Runtime API and is not portable unchanged to every GPU API. NVIDIA CUDA Quick Start Guide 13.5
Save the code as a `.cu` file and build in a supported CUDA Toolkit environment with `nvcc gpu_kernel.cu -o gpu_kernel`. On Windows, the output may be named `gpu_kernel.exe`.
Run `./gpu_kernel` on Linux or `.\gpu_kernel.exe` in PowerShell (prefix the executable with `.` and a backslash in PowerShell). Expected output: `GPU and CPU results match (n=1003)`.
A successful comparison means each of the 1003 GPU outputs matches the expected value calculated on the CPU. This checks function, not speed.
If `nvcc` is not found, check the Toolkit developer tools and `PATH`. If execution reports `no device` or a driver error, check the supported GPU and the driver, Toolkit, and platform combination.
For `illegal memory access` or a mismatch, inspect the index expression, `i < n` guard, allocation sizes, launch error, and synchronization error first. After fixing the issue, pass the same CPU comparison before measuring a real workload’s time and data-movement cost separately.
The program and commands are reference examples and were not compiled or run on a GPU while preparing this article. No speed claim is made for adding a small vector. Evaluate a kernel with representative work and the actual data flow on the target system. NVIDIA CUDA C++ Best Practices Guide
Sources
[NVIDIA CUDA Programming Guide — Programming Model](https://docs.nvidia.com/cuda/cuda-programming-guide/01-introduction/programming-model.html)
[NVIDIA CUDA Programming Guide — Intro to CUDA C++](https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/intro-to-cuda-cpp.html)
[NVIDIA CUDA Quick Start Guide 13.5](https://docs.nvidia.com/cuda/cuda-quick-start-guide/)