Zig Mutexes & Atomics
As long as each thread works on its own data, threads are easy. The trouble starts when two of them touch the same memory and at least one of them writes. That’s a data race, and it’s one of the nastiest bugs there is: the program compiles, often gives the right answer, and then one day it doesn’t. This page shows a real race losing updates, then the two standard fixes in Zig 0.17: a mutex (std.Io.Mutex) and atomics (std.atomic.Value).
A data race you can watch
Section titled “A data race you can watch”Four threads each add 1 to a shared counter a million times. The answer should be 4,000,000:
const std = @import("std");
var counter: u64 = 0;
fn addMany() void { for (0..1_000_000) |_| { counter += 1; }}
pub fn main() !void { var threads: [4]std.Thread = undefined; for (&threads) |*t| t.* = try std.Thread.spawn(.{}, addMany, .{}); for (threads) |t| t.join(); std.debug.print("counter = {d} (expected 4000000)\n", .{counter});}We ran it five times in a debug build on a 4-core machine. You’ll see something like:
counter = 1687213 (expected 4000000)counter = 1484401 (expected 4000000)counter = 1618524 (expected 4000000)counter = 1366848 (expected 4000000)counter = 1370558 (expected 4000000)More than half the additions vanished, and the number is different every time. Here’s why. counter += 1 looks like one step, but the CPU does three:
- read
counterfrom memory into a register, - add 1 to the register,
- write the register back to memory.
Now picture two threads doing this at the same moment:
| Thread A | Thread B | counter in memory |
|---|---|---|
| reads 41 | 41 | |
| reads 41 | 41 | |
| adds 1, writes 42 | 42 | |
| adds 1, writes 42 | 42 |
Two additions, but the counter only went up by one. Multiply that by millions and you get the numbers above.
Fix 1: a mutex
Section titled “Fix 1: a mutex”A mutex (“mutual exclusion”) is a lock that only one thread can hold at a time. Any thread that wants the counter must lock first; if someone else holds the lock, it waits. The read, add and write then happen as one unbroken step.
Since Zig 0.16 the mutex lives in std.Io (it used to be std.Thread.Mutex), because waiting for a lock is a kind of waiting the io should know about. So locking takes io:
const std = @import("std");const Io = std.Io;
const Counter = struct { mutex: Io.Mutex = .init, value: u64 = 0,
fn add(c: *Counter, io: Io) void { c.mutex.lockUncancelable(io); defer c.mutex.unlock(io); c.value += 1; }};
fn addMany(io: Io, counter: *Counter) void { for (0..1_000_000) |_| counter.add(io);}
pub fn main(init: std.process.Init) !void { const io = init.io; var counter: Counter = .{};
var threads: [4]std.Thread = undefined; for (&threads) |*t| t.* = try std.Thread.spawn(.{}, addMany, .{ io, &counter }); for (threads) |t| t.join();
std.debug.print("counter = {d}\n", .{counter.value});}Output:
counter = 4000000Right every time. A few habits worth copying from this example:
- Keep the mutex next to the data it protects, in the same struct. Then it’s obvious which lock goes with which data.
- Release the lock with a
deferon the very next line, likeadddoes. If you release it by hand at the end instead, an earlyreturnor a failingtrycan skip that line, the lock stays held forever, and every other thread waits forever. - Lock as briefly as you can. While one thread holds the lock, the others wait. Do slow work (I/O, big calculations) outside the locked part.
There are two ways to lock. lockUncancelable(io) just waits. lock(io) can also return error.Canceled if the task holding it is canceled, so you write try mutex.lock(io);. With plain threads that are never canceled, lockUncancelable is simpler. Inside io.async tasks, use try lock so cancel requests work.
Fix 2: atomics
Section titled “Fix 2: atomics”For a single number, a mutex is a bit heavy. CPUs have special atomic instructions that do a read-change-write as one step that no other core can interrupt. In Zig you use them through std.atomic.Value(T):
const std = @import("std");
var counter: std.atomic.Value(u64) = .init(0);
fn addMany() void { for (0..1_000_000) |_| { _ = counter.fetchAdd(1, .monotonic); }}
pub fn main() !void { var threads: [4]std.Thread = undefined; for (&threads) |*t| t.* = try std.Thread.spawn(.{}, addMany, .{}); for (threads) |t| t.join(); std.debug.print("counter = {d}\n", .{counter.load(.monotonic)});}Output:
counter = 4000000std.atomic.Value(u64) wraps the number so you can’t accidentally use plain += on it. The methods you’ll use most:
| Method | Does |
|---|---|
load(order) |
read the value |
store(value, order) |
write the value |
fetchAdd(n, order), fetchSub(n, order) |
add or subtract, return the old value |
swap(value, order) |
write, return the old value |
cmpxchgStrong(expected, new, ok_order, fail_order) |
write new only if the value is still expected |
Atomics only protect one value at a time. If two values must change together (say, moving money between two accounts), use a mutex around both.
That .monotonic argument: memory order
Section titled “That .monotonic argument: memory order”Every atomic operation takes a memory order. It answers the question “what does this operation promise about other memory around it?” You only need three:
.monotonic: “just make this one value safe.” Perfect for counters and statistics where nothing else depends on the value..releaseon a store and.acquireon a load: a hand-off. Everything the first thread wrote before its release store is visible to the second thread after its acquire load sees the stored value..seq_cst: the strictest. If you’re unsure, it’s the safe choice, at some cost in speed.
Here’s the hand-off in action. One thread prepares a message, then raises a flag; the other waits for the flag, then reads the message:
const std = @import("std");
var message: []const u8 = "";var ready: std.atomic.Value(bool) = .init(false);
fn writer() void { message = "the data is ready"; ready.store(true, .release);}
fn reader() void { while (!ready.load(.acquire)) std.atomic.spinLoopHint(); std.debug.print("reader saw: {s}\n", .{message});}
pub fn main() !void { const r = try std.Thread.spawn(.{}, reader, .{}); const w = try std.Thread.spawn(.{}, writer, .{}); w.join(); r.join();}Output:
reader saw: the data is readyThe .release/.acquire pair is what guarantees the reader sees the new message and not the old empty string. With .monotonic on both, the flag itself would be fine, but the CPU would be free to make message show up late. (std.atomic.spinLoopHint() tells the CPU “I’m busy-waiting”, which saves power. For real programs, prefer waiting with std.Io.Event instead of spinning.)
Tasks share memory too
Section titled “Tasks share memory too”Everything here applies to io.async tasks as well, because with the default init.io they run on real threads. Here four tasks in a group add to one total, protected by a mutex, and they use try lock because tasks can be canceled:
const std = @import("std");const Io = std.Io;
const Tally = struct { mutex: Io.Mutex = .init, total: u64 = 0,};
fn addUp(io: Io, tally: *Tally, amount: u64) Io.Cancelable!void { for (0..100_000) |_| { try tally.mutex.lock(io); defer tally.mutex.unlock(io); tally.total += amount; }}
pub fn main(init: std.process.Init) !void { const io = init.io; var tally: Tally = .{};
var group: Io.Group = .init; defer group.cancel(io); for (1..5) |i| group.async(io, addUp, .{ io, &tally, i }); try group.await(io);
std.debug.print("total = {d}\n", .{tally.total});}Output:
total = 1000000The amounts are 1, 2, 3 and 4, each added 100,000 times: (1 + 2 + 3 + 4) × 100,000 = 1,000,000. Drop the lock and you’d be back to random answers.
Catching races with ThreadSanitizer
Section titled “Catching races with ThreadSanitizer”Races are hard to spot by reading code, so let a tool look for them. Zig can build your program with ThreadSanitizer, which watches every memory access while the program runs:
zig build-exe race.zig -fsanitize-thread./raceOn the racy counter from the top of the page (with a smaller loop, because the checks slow things down a lot), you’ll see something like:
WARNING: ThreadSanitizer: data race (pid=18930) Read of size 8 at 0x55784b95f490 by thread T2: #0 race.addMany race.zig:7:9 Previous write of size 8 at 0x55784b95f490 by thread T1: #0 race.addMany race.zig:7:17 Location is global 'race.counter' of size 8...ThreadSanitizer: reported 2 warningsIt points right at counter += 1. Even better: in that run the final count happened to be correct, and ThreadSanitizer still caught the race. The mutex and atomic versions run without a single warning. It’s worth running your threaded code this way once in a while.
Deadlocks: the other way locks go wrong
Section titled “Deadlocks: the other way locks go wrong”Locks fix races, but bring a new problem: deadlock, where threads wait for each other forever and the program just hangs. The two classic causes:
- Locking the same mutex twice in one thread.
std.Io.Mutexis not “re-entrant”: the secondlockwaits for the first to be released, which never happens. - Two locks, opposite order. Thread A locks
xthen waits fory; thread B locksythen waits forx. Both wait forever. The fix is to always take locks in the same order everywhere.
When a threaded program hangs and uses no CPU, suspect a deadlock first.
Other tools in std.Io
Section titled “Other tools in std.Io”You won’t need these on day one, but it helps to know they exist. All of them take io:
| Type | Use it when |
|---|---|
std.Io.RwLock |
many threads read, few write (lockShared for readers, lock for writers) |
std.Io.Event |
one thread waits until another says “go” |
std.Io.Condition |
wait for a condition while holding a mutex |
std.Io.Semaphore |
allow at most N threads into a section |
std.Io.Queue(T) |
pass values between tasks safely (Zig Async & Futures uses one) |
The 0.16.0 release notes on sync primitives list where each one came from.
Practice
Section titled “Practice”1. Fix the race with an atomic
Section titled “1. Fix the race with an atomic”This program has a race. Fix it with std.atomic.Value so it always prints hits = 200000.
const std = @import("std");
var hits: u32 = 0;
fn visit() void { for (0..100_000) |_| hits += 1;}
pub fn main() !void { const a = try std.Thread.spawn(.{}, visit, .{}); const b = try std.Thread.spawn(.{}, visit, .{}); a.join(); b.join(); std.debug.print("hits = {d}\n", .{hits});}Hint: var hits: std.atomic.Value(u32) = .init(0); and _ = hits.fetchAdd(1, .monotonic);.
Show solution
const std = @import("std");
var hits: std.atomic.Value(u32) = .init(0);
fn visit() void { for (0..100_000) |_| _ = hits.fetchAdd(1, .monotonic);}
pub fn main() !void { const a = try std.Thread.spawn(.{}, visit, .{}); const b = try std.Thread.spawn(.{}, visit, .{}); a.join(); b.join(); std.debug.print("hits = {d}\n", .{hits.load(.monotonic)});}Output:
hits = 200000fetchAdd does the read, add and write as one step, so no update is lost. .monotonic is enough because nothing else depends on the counter.
2. A shared list with a mutex
Section titled “2. A shared list with a mutex”Two threads each append the numbers 1 to 3 to a shared std.ArrayList(u32). Protect it with an Io.Mutex and print how many items the list has at the end.
Hint: put the list and the mutex in one struct. Inside the lock, call list.append(gpa, n). init.gpa is safe to use from several threads.
Show solution
const std = @import("std");const Io = std.Io;
const Shared = struct { mutex: Io.Mutex = .init, list: std.ArrayList(u32) = .empty,};
fn fill(io: Io, gpa: std.mem.Allocator, shared: *Shared) !void { for (1..4) |n| { shared.mutex.lockUncancelable(io); defer shared.mutex.unlock(io); try shared.list.append(gpa, @intCast(n)); }}
pub fn main(init: std.process.Init) !void { var shared: Shared = .{}; defer shared.list.deinit(init.gpa);
const a = try std.Thread.spawn(.{}, fill, .{ init.io, init.gpa, &shared }); const b = try std.Thread.spawn(.{}, fill, .{ init.io, init.gpa, &shared }); a.join(); b.join();
std.debug.print("{d} items\n", .{shared.list.items.len});}Output:
6 itemsThe order of the items can differ between runs, but there are always 6. Without the lock, two appends at the same moment could corrupt the list.
- A data race is two threads touching the same memory, at least one writing, with nothing coordinating them. It loses updates and is illegal behavior.
- A race can look fine in a test or a
fastbuild. Don’t trust it. std.Io.Mutex(formerlystd.Thread.Mutex):lockUncancelable(io)ortry lock(io), then release it in adeferon the next line. Keep the mutex next to its data.std.atomic.Value(T)gives one-stepload,store,fetchAdd,swapandcmpxchgfor a single value.- Memory order:
.monotonicfor counters,.release/.acquirefor hand-offs,.seq_cstwhen unsure. - Build with
-fsanitize-threadto catch races, and take locks in a fixed order to avoid deadlocks.
Next up: Zig and C, why Zig and C get along so well and how C’s types look from Zig.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Sync primitives (0.16.0 release notes): the move from
std.Threadtostd.Iofor mutexes, conditions, events and more. - Atomics in the 0.17.1 reference: the
@atomicLoad,@atomicStore,@atomicRmwand@cmpxchgbuiltins thatstd.atomic.Valuewraps. - std/atomic.zig source (0.17.1): every method of
std.atomic.Value. - Mara Bos: Rust Atomics and Locks, chapter 3 (Memory Ordering): a clear, free explanation of memory orders. The examples are Rust, but the orders are the same ones Zig uses.