Skip to content

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.

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 thread
hello from the second thread
both done

spawn takes three things:

  1. A config struct. .{} means “the defaults”, which is almost always what you want. (You can set .stack_size if a thread needs more or less than the default 16 MB of stack.)
  2. The function the thread runs.
  3. 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.

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 = 49999995000000

The important bits:

  • for (&threads, &results, 0..) |*t, *r, i| walks both arrays at once with pointers, so each thread gets a pointer r to its own slot. No two threads write to the same memory.
  • The last chunk goes all the way to n, so nothing is lost when n doesn’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.

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 done

saved! 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.

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 going

The 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.

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 cores

Threads 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.

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 mode

That’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.

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.

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: 200

Each thread writes to its own variable, and we only read them after both join calls.

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 numbers

Same pattern as before: one slot per thread, join everything, then combine.

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:

written

Without 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 use try.
  • thread.join() waits for it to finish. Every thread needs a join (or, rarely, detach), or it’s killed when main returns.
  • Thread functions return void or !void: get results back through pointers, one slot per thread, read after join.
  • 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.async is often the better fit for tasks with results; std.Thread.Pool was removed in 0.16.

Next up: Zig Mutexes & Atomics, what goes wrong when threads share data, and the tools that fix it.

Quick check

1. What happens to a spawned thread that is still running when main returns?
2. How do you get a computed value out of a thread?
3. A thread function returns error.FileNotFound. What does the main thread see?
4. Two threads each print a line. In what order do the lines appear?