Skip to content

Mojo Parallelize

SIMD and vectorize make one CPU core do more per step. But your computer has several cores, and a normal program only uses one of them. parallelize splits work into numbered tasks and runs them on all cores at the same time. It’s the simplest way to multi-thread in Mojo: no threads to create, no locks to manage. It does come with one big rule about shared data, and this page is honest about both the speedup and the cost.

In Mojo 1.2, parallelize isn’t in the standard library. It lives in the max package from Modular, the company behind Mojo, under max.algorithm. If you only installed mojo, this import fails:

hello.mojo:1:6: error: unable to locate module 'max'
from max.algorithm import parallelize
^
mojo: error: failed to parse the provided Mojo source module

Add it to your project once, next to mojo:

Terminal window
uv add max

(With pixi it’s pixi add max.) The download is bigger than Mojo alone, because max also contains Modular’s AI tools, but you only need the small part used here. The parallelize reference is in the MAX docs for the same reason.

from std.runtime import parallelism_level
from std.sys import num_physical_cores, num_logical_cores
def main():
print("physical cores:", num_physical_cores())
print("logical cores: ", num_logical_cores())
print("worker threads:", parallelism_level())

You’ll see something like this (on our test machine, a 4-core VM):

physical cores: 4
logical cores: 4
worker threads: 4

Your numbers will differ. “Logical” cores include hyper-threads, so on many laptops that number is twice the physical one. parallelism_level() is how many worker threads Mojo’s runtime has ready for parallelize.

parallelize(func, n) calls func(0), func(1) … func(n - 1), spread over the worker threads, and returns once all of them are done:

from max.algorithm import parallelize
def main():
def work(i: Int):
print("task", i)
parallelize(work, 8)
print("all done")

You’ll see something like this. Here are two runs on our test machine:

task 0
task 1
task 4
task 5
task 2
task 3
task 6
task 7
all done
task 0
task 1
task 2
task 3
task 4
task 5
task 6
task 7
all done

The tasks can run in any order, and the order changes from run to run. That’s what running at the same time means. The only promise is the last line: parallelize waits, so all done always comes after every task. (Printing from several threads works for a demo like this, but don’t rely on the lines coming out in a useful order.)

To collect results, give every task its own slot in a list that already has the right length:

from max.algorithm import parallelize
def main():
var squares = List[Int](length=8, fill=0)
def work(i: Int) {mut squares}:
squares[i] = i * i
parallelize(work, len(squares))
print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49]

List[Int](length=8, fill=0) makes the 8 slots up front. Task i only ever writes squares[i], so no two tasks touch the same value, and the result is the same every time even though the order isn’t. Don’t append inside a task: appending can move the list’s memory while another task is writing to it.

Here’s what goes wrong if every task updates the same variable:

from max.algorithm import parallelize
from std.benchmark import keep
def main():
var total = 0
def work(i: Int) {mut total}:
for _ in range(100000):
total += 1
keep(total)
parallelize(work, 8)
print("expected 800000, got", total)

You’ll see something like this (three runs on our test machine; yours will be different, and that’s the problem):

expected 800000, got 635828
expected 800000, got 522603
expected 800000, got 738242

This is a data race. total += 1 is really three steps: read total, add 1, write it back. When two tasks do that at the same moment, both read the same old value and one of the additions is lost. The compiler doesn’t stop you: {mut total} compiles fine. (The keep(total) line is only there so the compiler can’t replace the loop with one big addition and hide the bug; you’ll meet keep in the next lesson.)

You have two fixes. The better one is the slot pattern above: give each task its own partial result and combine them after parallelize returns. The other is an atomic value, which the CPU updates in one step that can’t be interrupted:

from max.algorithm import parallelize
from std.atomic import Atomic
def main():
var total = Atomic[Int](0)
def work(i: Int) {mut total}:
for _ in range(100000):
total += 1
parallelize(work, 8)
print(total.load())

Output:

800000

Atomics are correct, but they’re slow when all cores fight over one value, so use them for a few updates, not for millions.

Most work isn’t “one task per item”. You split the data into a few big chunks, one task per chunk, and combine the chunk results at the end. Here’s a sum of square roots up to 4 million, in 8 chunks:

from max.algorithm import parallelize
from std.math import sqrt
comptime N = 4_000_000
comptime CHUNKS = 8
def chunk_sum(start: Int, end: Int) -> Float64:
var s: Float64 = 0
for i in range(start, end):
s += sqrt(Float64(i))
return s
def main():
var partial = List[Float64](length=CHUNKS, fill=0)
def one_chunk(c: Int) {mut partial}:
var size = N // CHUNKS
partial[c] = chunk_sum(c * size, (c + 1) * size)
parallelize(one_chunk, CHUNKS)
var total: Float64 = 0
for x in partial:
total += x
print("parallel:", total)
print("serial: ", chunk_sum(0, N))

Output:

parallel: 5333332333.1255045
serial: 5333332333.125122

Look at the last digits: they’re not the same. Nothing is broken. Floats round a tiny bit on every addition, and adding in 8 groups rounds differently from adding in one long line. The parallel result is still the same on every run, because each chunk is always the same range and the chunks are combined in the same order. Keep that in mind when you compare results: check that they’re close, not identical.

(This example divides evenly: 4,000,000 is a multiple of 8. With other sizes, the last chunk needs to run up to N so nothing is skipped.)

Here’s the chunked sum timed on one core and with parallelize, for a big job and a tiny one:

from max.algorithm import parallelize
from std.math import sqrt
from std.benchmark import run, keep, Unit
def chunk_sum(start: Int, end: Int) -> Float64:
var s: Float64 = 0
for i in range(start, end):
s += sqrt(Float64(i))
return s
def compare(n: Int) raises:
comptime CHUNKS = 8
var partial = List[Float64](length=CHUNKS, fill=0)
def one_chunk(c: Int) {mut partial, imm n}:
var size = n // CHUNKS
partial[c] = chunk_sum(c * size, (c + 1) * size)
def serial() {imm n}:
keep(chunk_sum(0, n))
def parallel() {imm one_chunk}:
parallelize(one_chunk, CHUNKS)
var s = run(serial, max_runtime_secs=1.0)
var p = run(parallel, max_runtime_secs=1.0)
print("n =", n, " one core:", round(s.mean(Unit.ms), 4), "ms parallel:", round(p.mean(Unit.ms), 4), "ms")
def main() raises:
compare(4_000_000)
compare(800)

You’ll see something like this (one run on our test machine, a 4-core VM that was also running other work; your numbers will be different):

n = 4000000 one core: 7.5137 ms parallel: 3.7211 ms
n = 800 one core: 0.0016 ms parallel: 0.0101 ms

Over several runs, the big job was between about 1.5 and 3 times faster with parallelize on this machine. That’s less than 4 times, even with 4 cores: starting tasks and waiting for the slowest one costs time, and the other programs on the VM took their share. The tiny job tells the other half of the story: with only 800 square roots, parallelize was slower, in some runs by a factor of a hundred. Handing work to other threads has a fixed cost, and for small jobs that cost is bigger than the work.

You can also limit how many threads it uses with a third argument, parallelize(func, n, num_workers), for example to leave one core free for something else.

Fill a list of 10 slots so that slot i holds i * i * i, using parallelize with one task per slot. Print the list.

Hint: make the list with List[Int](length=10, fill=0) and capture it with mut.

Show solution
from max.algorithm import parallelize
def main():
var cubes = List[Int](length=10, fill=0)
def work(i: Int) {mut cubes}:
cubes[i] = i * i * i
parallelize(work, len(cubes))
print(cubes)

Output:

[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

Every task writes only its own slot, so the result is the same on every run.

Count how many numbers from 0 to 999,999 are divisible by 7, using 4 chunks and parallelize. Don’t share a counter between tasks.

Hint: each task counts its own range into counts[c]; add up counts afterwards.

Show solution
from max.algorithm import parallelize
comptime N = 1_000_000
comptime CHUNKS = 4
def main():
var counts = List[Int](length=CHUNKS, fill=0)
def count_chunk(c: Int) {mut counts}:
var size = N // CHUNKS
var found = 0
for i in range(c * size, (c + 1) * size):
if i % 7 == 0:
found += 1
counts[c] = found
parallelize(count_chunk, CHUNKS)
var total = 0
for n in counts:
total += n
print(counts)
print(total)

Output:

[35715, 35714, 35714, 35715]
142858

Each task counts into its own local found and writes it once at the end. Combining four numbers afterwards is cheap and has no race.

  • In Mojo 1.2, parallelize comes from the max package: uv add max, then from max.algorithm import parallelize.
  • parallelize(func, n) runs func(0) to func(n - 1) on several cores, in any order, and returns when all tasks are done.
  • Collect results with one slot per task in a list made with List[T](length=n, fill=...); never append from tasks.
  • Several tasks writing the same variable is a data race that loses updates. Use per-task results, or Atomic for a few updates.
  • Split big work into chunks; float results can differ slightly from a serial sum because of rounding order.
  • It only pays off for big jobs: on our 4-core test VM a 4-million-item job ran about 1.5 to 3 times faster, and an 800-item job ran slower. Measure your own.

Next up: benchmarking, how to time code honestly so numbers like these mean something.

Quick check

1. Where does parallelize come from in Mojo 1.2?
2. Eight tasks each do total += 1 on the same captured Int 100,000 times. What happens?
3. What is the safest way to collect one result per task?
4. You parallelize a job that takes 2 microseconds on one core. What should you expect?