parallelize 函数
跨线程运行循环迭代
parallelize 函数 是 CoddyKit 上的免费 Mojo Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Mojo Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Mojo Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
One Core Is Not Enough
A plain loop runs on a single core while the rest sit idle. For heavy work, that wastes most of your CPU.
for i in range(n):
out[i] = heavy(i)Spread the Work
Parallelism means handing different loop iterations to different cores so they all work at the same time. 🧵
Meet parallelize
Mojo's parallelize helper runs your loop body across many threads for you, so you skip the manual thread plumbing.
from algorithm import parallelizeThe Work Closure
You write a small function that does the work for one index. Mojo calls it many times, once per iteration.
fn work(i: Int):
out[i] = heavy(i)Pass the Closure as a Parameter
The closure goes in square brackets as a compile-time parameter, not as a normal call argument. Mojo specializes on it.
parallelize[work](n)The Count Is Runtime
The number in the parentheses is how many work items to run. That count is an ordinary runtime value.
parallelize[work](num_items)Ask the Machine for Cores
Use num_physical_cores from the sys module to learn how many real cores you have to spread work across.
from sys import num_physical_coresCap the Worker Count
An optional second argument sets how many workers run at once. Matching it to your cores often works best.
parallelize[work](n, num_physical_cores())Each Call Is Independent
parallelize assumes work items do not depend on each other's order. Each call should stand on its own.
Best for Heavy Loops
Parallelism shines when each item does real work. For tiny loops, the thread overhead can cost more than it saves.
Measure the Speedup
Time the loop before and after going parallel. A real benchmark tells you whether the extra threads actually helped.
Quick Check
You want to run a loop body across several CPU cores in Mojo.
Recap
You import parallelize, pass a per-item closure as a bracket parameter and the count in parentheses, then size workers to your cores for a real speedup. 🚀
常见问题解答
「parallelize 函数」课时是免费的吗?
是的 — 「parallelize 函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Mojo Academy 课程的其余内容,请升级到 CoddyKit PRO。 Mojo Academy 课程共包含 4 节课。
「parallelize 函数」这节课中我会学到什么?
跨线程运行循环迭代 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Mojo Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Mojo Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「parallelize 函数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Mojo Academy 课中编写并运行代码吗?
能。每节 Mojo Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。