Skip to content
systemcoding.dev
GPU

Declare a CUDA kernel with __global__

Mark a function __global__ in CUDA 12 so the host launches it and the device runs it, returning void, and see which qualifiers may call which.

1 min read
Summarize in AI

A CUDA kernel is an ordinary function with one qualifier in front of it. __global__ means "called from the host, runs on the device", and that decides everything else about it: it must return void, it cannot be a member of a class that is not static, and you start it with the launch syntax rather than a call. CUDA 12.

scale.cucuda
#include <cstdio>

__global__ void scale(float *x, float k, int n)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) x[i] *= k;
}

int main()
{
    float h[4] = {1, 2, 3, 4};
    float *d;
    cudaMalloc(&d, sizeof h);
    cudaMemcpy(d, h, sizeof h, cudaMemcpyHostToDevice);
    scale<<<1, 4>>>(d, 2.0f, 4);
    cudaMemcpy(h, d, sizeof h, cudaMemcpyDeviceToHost);
    printf("%g %g %g %g\n", h[0], h[1], h[2], h[3]);
    cudaFree(d);
    return 0;
}
Text
2 4 6 8

The qualifiers are summarised in the CUDA C++ Programming Guide. __device__ functions run on the device and are called only from device code; __host__ is the default. A __global__ function may also be called from another kernel when you build with dynamic parallelism, but that is a separate feature.

The launch is asynchronous: control returns before the kernel finishes, and the later cudaMemcpy is what waits for it. Compile with nvcc scale.cu -o scale. The if (i < n) guard is there because a grid is rounded up to whole blocks.

Share

More snippets

GPU

List platforms with clGetPlatformIDs

Call clGetPlatformIDs twice, once for the count and once for the handles, then print each platform name with clGetPlatformInfo in OpenCL 3.0 C.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.