Zig Threads
A thread is a separate line of execution inside your program. Your program starts with one (the main thread), and you can ask the operating system for more. Each thread runs its own function, at the same time as the others, on another CPU core if one is free. All threads share the same memory, which is what makes them useful and also what makes them tricky. This page covers std.Thread: starting threads, giving them work, collecting results and waiting for them to finish.
Spawn and join
Section titled “Spawn and join”Two calls do most of the work. std.Thread.spawn starts a thread, and join waits for it to finish:
const std = @import("std");
fn greet(name: []const u8) void { std.debug.print("hello from the {s} thread\n", .{name});}
pub fn main() !void { const t = try std.Thread.spawn(.{}, greet, .{"second"}); std.debug.print("hello from the main thread\n", .{}); t.join(); std.debug.print("both done\n", .{});}You’ll see something like:
hello from the main threadhello from the second threadboth donespawn takes three things:
- A config struct.
.{}means “the defaults”, which is almost always what you want. (You can set.stack_sizeif a thread needs more or less than the default 16 MB of stack.) - The function the thread runs.
- A tuple with that function’s arguments.
It returns a std.Thread, and it can fail (for example if the system won’t give you any more threads), hence the try.
The first two lines can come out in either order. Once a thread is started, the operating system decides when each thread runs, so “hello from the main thread” usually wins here because the main thread is already running, but nothing guarantees it. What is guaranteed is the last line: t.join() doesn’t return until greet has finished, so both done always comes last.
Getting results back
Section titled “Getting results back”A thread function can’t return a value to you. It must return void (or !void, more on that below). Try returning a number and the compiler stops you:
const std = @import("std");
fn square(x: u64) u64 { return x * x;}
pub fn main() !void { const t = try std.Thread.spawn(.{}, square, .{12}); t.join();}.../std/Thread.zig:427:17: error: expected return type of startFn to be 'u8', 'noreturn', '!noreturn', 'void', or '!void'(u8 is allowed because some systems use it as the thread’s exit code, but you can’t read it back from Zig.) The usual pattern is to pass a pointer to where the answer should go. Here four threads each add up a quarter of a big range and write their part into their own slot:
const std = @import("std");
fn sumRange(from: u64, to: u64, result: *u64) void { var total: u64 = 0; var i = from; while (i < to) : (i += 1) total += i; result.* = total;}
pub fn main() !void { const n: u64 = 10_000_000; const parts = 4; var results: [parts]u64 = undefined; var threads: [parts]std.Thread = undefined;
const chunk = n / parts; for (&threads, &results, 0..) |*t, *r, i| { const from = i * chunk; const to = if (i == parts - 1) n else from + chunk; t.* = try std.Thread.spawn(.{}, sumRange, .{ from, to, r }); } for (threads) |t| t.join();
var total: u64 = 0; for (results) |r| total += r; std.debug.print("sum of 0..{d} = {d}\n", .{ n, total });}Output:
sum of 0..10000000 = 49999995000000The important bits:
for (&threads, &results, 0..) |*t, *r, i|walks both arrays at once with pointers, so each thread gets a pointerrto its own slot. No two threads write to the same memory.- The last chunk goes all the way to
n, so nothing is lost whenndoesn’t split evenly. - All the joins happen before we read
results. Reading a slot before its thread has finished would give you garbage.
Zig has no closures, so a thread can’t “see” your local variables by itself. Everything it needs goes in through the argument tuple, usually as values or pointers.
Always join (or detach)
Section titled “Always join (or detach)”What happens if you never call join? The program doesn’t wait:
const std = @import("std");
fn slowSave(io: std.Io) void { io.sleep(.fromMilliseconds(500), .awake) catch {}; std.debug.print("saved!\n", .{});}
pub fn main(init: std.process.Init) !void { _ = try std.Thread.spawn(.{}, slowSave, .{init.io}); std.debug.print("main is done\n", .{});}Output:
main is donesaved! never appears. When main returns, the whole process ends, and every other thread is killed on the spot, halfway through whatever it was doing. If that was writing a file, the file is now half-written.
Every thread you spawn needs exactly one of these:
join(): wait for it to finish. This is what you want 99% of the time.detach(): “I won’t wait for this one; clean yourself up when you’re done.” Useful only for threads that may outlive the work that started them, and the process ending still kills them.
Notice that the thread called io.sleep. Threads can use the same io as the rest of your program: pass init.io in the argument tuple like anything else.
Errors inside a thread
Section titled “Errors inside a thread”A thread function may return !void. But nobody receives that error: join returns nothing. Zig prints it and the thread ends:
const std = @import("std");
fn openConfig(io: std.Io) !void { const file = try std.Io.Dir.cwd().openFile(io, "missing.conf", .{}); file.close(io);}
pub fn main(init: std.process.Init) !void { const t = try std.Thread.spawn(.{}, openConfig, .{init.io}); t.join(); std.debug.print("main keeps going\n", .{});}You’ll see something like this (in a debug build, with an error trace in the middle):
error: FileNotFound.../std/Io/Dir.zig:581:5: 0x1038140 in openFile (std.zig) return io.vtable.dirOpenFile(io.userdata, dir, sub_path, options); ^main.zig:4:18: 0x11f10b2 in openConfig (main.zig) const file = try std.Io.Dir.cwd().openFile(io, "missing.conf", .{}); ^main keeps goingThe main thread has no idea anything went wrong. If the error matters, catch it inside the thread and store it somewhere the main thread can check after join, the same way you stored results above. This is one place where io.async from Zig Async & Futures is nicer: await hands you the task’s error directly.
How many threads?
Section titled “How many threads?”More threads than CPU cores doesn’t make computing faster; the cores just take turns. std.Thread.getCpuCount() tells you how many logical cores the machine has, a good upper limit for number-crunching work:
const std = @import("std");
pub fn main() !void { const cores = try std.Thread.getCpuCount(); std.debug.print("this machine has {d} logical cores\n", .{cores});}On the 4-core machine this site is tested on, you’ll see:
this machine has 4 logical coresThreads that mostly wait (for the network, for files) are different: there, the real question is how many things you want to wait on at once, and io.async usually handles that better than a big pile of threads.
Single-threaded builds
Section titled “Single-threaded builds”Zig can build programs that have no threads at all (the -fsingle-threaded flag, or targets like plain WebAssembly). In such a build spawn is a compile error:
.../std/Thread.zig:346:9: error: Cannot spawn thread when building in single-threaded modeThat’s another reason library code often prefers io.async: it still works in a single-threaded build, just without the parallelism. The language reference on single-threaded builds lists what else changes.
Threads or io.async?
Section titled “Threads or io.async?”Both run code at the same time. A rough guide:
| You want to… | Use |
|---|---|
| Run independent tasks and get their results or errors back | io.async + await |
| Wait on many things at once (files, network) | io.async / std.Io.Group |
Code that should also work single-threaded or with other Io implementations |
io.async |
| Full control: a long-lived worker thread, its stack size, its lifetime | std.Thread.spawn |
| Split a big computation over CPU cores in a small program | either; std.Thread is simple and obvious |
Older Zig had std.Thread.Pool for running many small jobs on a few threads. It was removed in 0.16; the release notes point to std.Io (async and groups) instead.
Practice
Section titled “Practice”1. Two workers
Section titled “1. Two workers”Spawn two threads that each run fn work(id: u32, out: *u32) void, which stores id * 100 into out. Join both, then print both results from the main thread.
Hint: make var a: u32 = 0; and var b: u32 = 0;, and pass &a and &b.
Show solution
const std = @import("std");
fn work(id: u32, out: *u32) void { out.* = id * 100;}
pub fn main() !void { var a: u32 = 0; var b: u32 = 0; const t1 = try std.Thread.spawn(.{}, work, .{ 1, &a }); const t2 = try std.Thread.spawn(.{}, work, .{ 2, &b }); t1.join(); t2.join(); std.debug.print("worker 1: {d}, worker 2: {d}\n", .{ a, b });}Output:
worker 1: 100, worker 2: 200Each thread writes to its own variable, and we only read them after both join calls.
2. Count the even numbers in parallel
Section titled “2. Count the even numbers in parallel”Split the numbers 0 to 999,999 into 4 parts and let each thread count how many even numbers are in its part. Add up the counts in main.
Hint: reuse the shape of sumRange, but count if (i % 2 == 0) instead of adding.
Show solution
const std = @import("std");
fn countEven(from: u64, to: u64, result: *u64) void { var count: u64 = 0; var i = from; while (i < to) : (i += 1) { if (i % 2 == 0) count += 1; } result.* = count;}
pub fn main() !void { const n: u64 = 1_000_000; var results: [4]u64 = undefined; var threads: [4]std.Thread = undefined; const chunk = n / 4;
for (&threads, &results, 0..) |*t, *r, i| { const from = i * chunk; const to = if (i == 3) n else from + chunk; t.* = try std.Thread.spawn(.{}, countEven, .{ from, to, r }); } for (threads) |t| t.join();
var total: u64 = 0; for (results) |r| total += r; std.debug.print("{d} even numbers\n", .{total});}Output:
500000 even numbersSame pattern as before: one slot per thread, join everything, then combine.
3. Don’t lose the work
Section titled “3. Don’t lose the work”This program should print written, but it doesn’t. Fix it.
const std = @import("std");
fn write(io: std.Io) void { io.sleep(.fromMilliseconds(100), .awake) catch {}; std.debug.print("written\n", .{});}
pub fn main(init: std.process.Init) !void { _ = try std.Thread.spawn(.{}, write, .{init.io});}Hint: keep the std.Thread that spawn returns.
Show solution
const std = @import("std");
fn write(io: std.Io) void { io.sleep(.fromMilliseconds(100), .awake) catch {}; std.debug.print("written\n", .{});}
pub fn main(init: std.process.Init) !void { const t = try std.Thread.spawn(.{}, write, .{init.io}); t.join();}Output:
writtenWithout join, main returned straight away and the process ended before the thread got to print.
std.Thread.spawn(.{}, function, .{args})starts a thread; it can fail, so usetry.thread.join()waits for it to finish. Every thread needs ajoin(or, rarely,detach), or it’s killed whenmainreturns.- Thread functions return
voidor!void: get results back through pointers, one slot per thread, read afterjoin. - Errors returned from a thread are printed and lost; catch them inside the thread if they matter.
- Output from several threads can come in any order.
io.asyncis often the better fit for tasks with results;std.Thread.Poolwas removed in 0.16.
Next up: Zig Mutexes & Atomics, what goes wrong when threads share data, and the tools that fix it.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- std/Thread.zig source (0.17.1):
spawn,join,detachandgetCpuCountwith their doc comments. - Single-threaded builds (0.17.1 reference): what changes when a program is built without threads.
- ThreadPool removed (0.16.0 release notes): why
std.Thread.Poolwent away and what to use now. - Sync primitives (0.16.0 release notes): where the old
std.Threadlocks and wait groups moved.