经典索引公式
blockIdx.x * blockDim.x + threadIdx.x
经典索引公式 是 CoddyKit 上的免费 CUDA Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 CUDA Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 CUDA Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
One Thread, One Element
The whole point of a CUDA kernel is that every thread handles one piece of data. To do that, each thread needs a unique global index.
Why Local IDs Are Not Enough
Inside a block, threadIdx.x only counts 0 up to blockDim minus one. Many blocks reuse those same small numbers, so it cannot be your final index.
Blocks Sit Side by Side
Picture the grid as blocks laid end to end. Each block owns a contiguous slice of the array, and blockIdx.x tells you which slice you are in.
How Wide Is a Block?
blockDim.x is the number of threads per block. It is the width of each slice, so it scales your block offset to the right spot.
The Classic Formula
Combine the three: skip past earlier blocks, then add your position inside this block. That single line gives every thread a unique index.
int i = blockIdx.x * blockDim.x + threadIdx.x;Walking Through It
With 4 threads per block, block 0 covers 0 to 3, block 1 covers 4 to 7, block 2 covers 8 to 11. The offsets never overlap.
A Concrete Example
Thread 2 in block 3 with blockDim 256 lands at 3 times 256 plus 2, which is 770. That is its global position in the data.
// blockIdx.x=3, blockDim.x=256, threadIdx.x=2
int i = 3 * 256 + 2; // i == 770Using the Index
Once you have i, you treat it as an array subscript. Each thread reads and writes only its own element, with no overlap.
out[i] = a[i] + b[i];It Maps One to One
Launch n threads and the formula produces every value from 0 to n minus 1 exactly once. That is a perfect one-to-one cover of the array.
The Order Matters
Always multiply before you add. blockIdx.x * blockDim.x is the start of your slice, and threadIdx.x is the step inside it.
Beyond One Dimension
The same idea extends to 2D and 3D using the .y and .z members, but for flat arrays the .x formula is all you need. 🚀
Quick Check
Compute one thread's global index.
Recap
You learned the formula every kernel uses: blockIdx.x * blockDim.x + threadIdx.x. It hands each thread one unique slot in your array. 🎉
常见问题解答
「经典索引公式」课时是免费的吗?
是的 — 「经典索引公式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 CUDA Academy 课程的其余内容,请升级到 CoddyKit PRO。 CUDA Academy 课程共包含 4 节课。
「经典索引公式」这节课中我会学到什么?
blockIdx.x * blockDim.x + threadIdx.x 你通过在浏览器中直接运行的动手代码来练习 CUDA Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 CUDA Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 CUDA Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「经典索引公式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 CUDA Academy 课中编写并运行代码吗?
能。每节 CUDA Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。