Zig Cookbook

Introduction

Thread pool

Thread pools address two different problems:

  1. They usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and
  2. They provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.

In this example, we spawn 10 tasks using Io.Group, and call await to wait for them to finish.

const std = @import("std");
const Io = std.Io;
const print = std.debug.print;

pub fn main(init: std.process.Init) !void {
    const io = init.io;

    var group: Io.Group = .init;
    errdefer group.cancel(io);

    for (0..10) |i| {
        group.async(io, run, .{i});
    }
    try group.await(io);

    print("All threads exit.\n", .{});
}

fn run(id: usize) void {
    print("I'm from {d}\n", .{id});
}