cudaDeviceSynchronize

Wait for all GPU work to finish

Syntax

cpp
1
cudaError_t cudaDeviceSynchronize(void);

Returns

cudaSuccess
All queued work finished without errors.
any execution error
The first error from work that was running, such as cudaErrorIllegalAddress or cudaErrorAssert.

How it works

When you need it

Reading cudaMallocManaged memory on the CPU after a kernel, timing kernels with a CPU clock, seeing device printf output before the program ends, and finding which kernel failed while debugging.

When you do not

Before a cudaMemcpy on the default stream, between kernels on the same stream (they already run in order), and before cudaFree, which also waits.

It is expensive in a loop

Each call stalls the CPU until the GPU is idle, so the CPU cannot queue the next launch in advance. Keep it out of hot loops in production code, or wait on one stream with cudaStreamSynchronize.

Launch errors vs execution errors

cudaGetLastError() after a launch catches a bad configuration. cudaDeviceSynchronize() catches what goes wrong while the kernel runs. Check both while debugging.

Example

Press Run to execute this on a real NVIDIA GPU in the playground.

Example: managed memory read before and after synchronizing
main.cu
1234567891011121314151617181920212223
#include <cstdio>
#include <cuda_runtime.h>

__global__ void slowWrite(int *flag) {
    long long start = clock64();
    while (clock64() - start < 200000000LL) {}   // about 0.1 s of work
    *flag = 42;
}

int main() {
    int *flag;
    cudaMallocManaged(&flag, sizeof(int));
    *flag = 0;

    slowWrite<<<1, 1>>>(flag);
    printf("before sync: %d\n", *flag);   // kernel still running

    cudaError_t err = cudaDeviceSynchronize();
    printf("after sync:  %d (%s)\n", *flag, cudaGetErrorString(err));

    cudaFree(flag);
    return 0;
}
Output on an NVIDIA T4
before sync: 0
after sync:  42 (no error)

Common mistakes

Timing a kernel without it

Without a sync, a CPU timer around kernel<<<...>>>() only measures the launch, not the work. Synchronize before stopping the timer, or use CUDA events.

Calling it after every launch in production

It makes errors easy to locate, but it removes the overlap between CPU and GPU. Keep it behind a debug flag.

FAQ

What is the difference between cudaDeviceSynchronize and cudaStreamSynchronize?

cudaDeviceSynchronize waits for all work on the GPU in every stream. cudaStreamSynchronize(stream) waits only for that one stream, so other streams keep running. cudaThreadSynchronize is the old, deprecated name for cudaDeviceSynchronize.

Why does my program work without cudaDeviceSynchronize?

If it copies results back with cudaMemcpy, that copy waits for the kernels first. Programs that only print from the kernel or use managed memory need the explicit call.

Does cudaDeviceSynchronize clear errors?

No. It reports them. A sticky error such as an illegal memory access keeps coming back from every later call until the process restarts.