Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Concurrency and Tooling

Threads and Synchronization

Run code in parallel in Zig with std.Thread.spawn and join, protect shared data with Mutex and atomics, use Condition, thread pools and WaitGroup, and avoid data races.

Zig gives you threads, locks and atomics in the standard library, and no hidden runtime: there is no garbage collector, no scheduler you did not ask for, and no implicit data-race protection. That means threads are a sharp tool. This lesson covers the basics and the habits that keep programs correct.

Zig's concurrency story is changing. Releases after 0.15 move async and I/O toward a new std.Io interface that is passed around like an allocator, and the old async/await keywords were removed. The thread primitives below (std.Thread, Mutex, Condition, atomics) are the stable foundation either way. Zig cannot run on this site, so the Zig blocks are read-only and the runnable stand-ins are in Go.

Spawning and joining

std.Thread.spawn starts a thread running a function. It takes a config struct, the function and a tuple of arguments, and returns a Thread handle. You must either join it (wait for it to finish) or detach it (let it run on its own). Forgetting both leaks the thread.

ZIG
const std = @import("std");

fn worker(id: u32) void {
    std.debug.print("hello from worker {d}\n", .{id});
}

pub fn main() !void {
    var threads: [4]std.Thread = undefined;
    for (&threads, 0..) |*t, i| {
        t.* = try std.Thread.spawn(.{}, worker, .{@as(u32, @intCast(i))});
    }
    for (threads) |t| t.join();
}

The order of the four lines is not guaranteed: the threads run in parallel. Spawning can fail (error.SystemResources), so try it. Each thread has its own stack, whose size you may set in the config (.{ .stack_size = 1024 * 1024 }).

Sharing data: the danger

Two threads writing the same variable without coordination is a data race, which is undefined behavior. This is wrong:

ZIG
var counter: u64 = 0; // shared and unprotected

fn bump() void {
    for (0..100_000) |_| counter += 1; // race: updates get lost
}

Run it on four threads and counter ends up lower than 400000, and differently each time. You have three honest fixes: don't share (give each thread its own data), lock, or use atomics.

Mutex

std.Thread.Mutex guarantees that only one thread at a time runs the code between lock and unlock. Always pair them with defer:

ZIG
var mutex: std.Thread.Mutex = .{};
var counter: u64 = 0;

fn bump() void {
    for (0..100_000) |_| {
        mutex.lock();
        defer mutex.unlock();
        counter += 1;
    }
}

Locking per increment is slow; in real code do bigger chunks of work per lock, or keep a per-thread total and merge at the end. A common design is a struct that bundles the data with its mutex and only exposes methods that lock.

ZIG
const SafeCounter = struct {
    mutex: std.Thread.Mutex = .{},
    value: u64 = 0,

    fn add(self: *SafeCounter, n: u64) void {
        self.mutex.lock();
        defer self.mutex.unlock();
        self.value += n;
    }
};

Zig's mutex is not recursive: locking it twice from the same thread deadlocks. Keep lock order consistent across your program (always A before B) to avoid deadlocks between two locks.

Atomics

A single counter does not need a lock. Atomic operations are indivisible:

ZIG
var hits = std.atomic.Value(u64).init(0);

fn record() void {
    _ = hits.fetchAdd(1, .monotonic);
}
// hits.load(.monotonic) reads the value

The second argument is the memory ordering. .monotonic is enough for plain counters. .acquire/.release pairs are used to publish data (the writer does a .release store, the reader a matching .acquire load), and .seq_cst is the safest and slowest. If you are not sure, use a mutex instead.

Waiting for a condition

When a thread must sleep until something becomes true (a queue is not empty), use std.Thread.Condition together with a mutex:

ZIG
mutex.lock();
defer mutex.unlock();
while (queue.items.len == 0) {
    cond.wait(&mutex); // unlocks, sleeps, relocks
}
const job = queue.orderedRemove(0);

Always wait in a loop: a thread may wake up spuriously, or another thread may have taken the item first. The producer pushes under the lock and calls cond.signal() (wake one) or cond.broadcast() (wake all).

Thread pools and wait groups

Creating a thread per task is expensive. A pool creates a fixed number of workers once and feeds them tasks:

ZIG
var pool: std.Thread.Pool = undefined;
try pool.init(.{ .allocator = gpa });
defer pool.deinit(); // waits for queued tasks

var wg: std.Thread.WaitGroup = .{};
for (0..8) |i| {
    pool.spawnWg(&wg, work, .{i});
}
wg.wait();

WaitGroup counts running tasks, and wait blocks until they all finish. (The thread pool and its exact methods are among the APIs most affected by the I/O changes in newer releases, so verify against your version's standard library.)

Thread-local storage

threadlocal var gives each thread its own copy of a global. It is the right tool for per-thread scratch buffers or counters that need no sharing.

ZIG
threadlocal var scratch: [256]u8 = undefined;

Patterns that work

flowchart LR
  P["producer threads"] -->|"push under lock"| Q["shared queue<br/>mutex + condition"]
  Q -->|"wait / pop"| W["worker threads"]
  W --> R["results<br/>per-thread, merge later"]

Caption: a classic producer-consumer design, with all sharing funneled through one locked queue.

  • Share nothing: split an array into chunks and give each thread a separate slice. No locks, no races. Merge results after join.
  • Message queues: one locked queue, many workers.
  • Immutable data: any number of threads may read data nobody mutates.
  • Allocators: DebugAllocator and page_allocator are thread-safe; for arenas and fixed buffers, check the documentation of your version before sharing them. Giving each thread its own arena is always safe.

Runnable stand-ins

Go's goroutines differ from OS threads, but the synchronization ideas are the same. First, the unsafe counter fixed with a mutex, and the chunked "share nothing" version that needs no lock at all:

Go Stand-in: mutex versus share-nothing chunks (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

And atomics, the lock-free counter:

Go Stand-in: atomic counter (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Spawning a thread and never joining or detaching it.
  • Forgetting defer mutex.unlock() and returning early with the lock held.
  • Waiting on a condition with if instead of while.
  • Sharing an arena allocator between threads.
  • Choosing atomics with weaker memory ordering without understanding it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must you do with a thread returned by std.Thread.spawn?

    A thread handle must be joined (wait) or detached; otherwise its resources leak.
  2. 2. Why is 'counter += 1' from several threads without a lock wrong?

    Unsynchronized concurrent writes are a data race. Use a mutex, an atomic, or do not share the variable.
  3. 3. How should you wait on a std.Thread.Condition?

    Wakeups can be spurious or the state may have changed, so recheck in a while loop with the mutex held.
  4. 4. What is the simplest way to avoid locks entirely?

    Disjoint data needs no synchronization.

Summary

  • std.Thread.spawn starts threads; always join or detach.
  • Protect shared data with std.Thread.Mutex (lock/defer unlock), use atomics for simple counters, and Condition in a loop for waiting.
  • Prefer designs that share nothing; use pools and wait groups for many small tasks.
  • Check how your Zig version exposes pools and async I/O.

Next: Testing in Zig