Hello, CUDA

第一个 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 / 内存模型这些,以后博客和专题里慢慢展开。

评论区
评论功能即将上线, 敬请期待。