Hello, CUDA

2026-06-10 · 约 2 分钟

第一个 CUDA 程序——完整的 hello.cu:

#include <stdio.h>

__global__ void hello() {
    printf("Hello, CUDA from thread %d\n", threadIdx.x);
}

int main() {
    hello<<<1, 8>>>();
    cudaDeviceSynchronize();
    return 0;
}

编译并运行:

nvcc hello.cu -o hello
./hello

应该看到 8 行 Hello, CUDA from thread N(顺序不固定,线程是并行的)。

几个关键字

  • __global__ —— 标记一个 kernel(GPU 上执行、host 上启动的函数)
  • threadIdx.x —— 当前线程的编号
  • <<<1, 8>>> —— 启动 1 个 block × 8 个 thread,一共 8 个线程
  • cudaDeviceSynchronize() —— 等 GPU 干完活再退出,否则 main 可能在 kernel 输出前就 return 了

跑出来就算入门成功。深入 grid / block / shared memory / warp / 内存模型这些,以后博客和专题里慢慢展开。

评论
评论功能尚未配置:在 GitHub 仓库开启 Discussions,并按项目 README 里的步骤填好 src/consts.ts 即可启用(基于 Giscus,评论需要 GitHub 账号)。