Skip to content

Zig Async & Futures

Programs spend a lot of time waiting: for a file, for a server to answer, for a timer. If you need three answers and each takes a second, waiting for them one after another takes three seconds, but asking for all three at once takes about one. In Zig 0.16 and later, that’s what io.async is for. There are no async or await keywords: you hand a normal function to your io, get back a future, and collect the result later. This page covers that, how to cancel work you no longer need, groups of tasks, and the important difference between async and concurrent.

Here’s a pretend “fetch” that just sleeps, so you can see the timing. We fetch two things at once:

const std = @import("std");
const Io = std.Io;
fn fetch(io: Io, name: []const u8, ms: i64) ![]const u8 {
try io.sleep(.fromMilliseconds(ms), .awake);
return name;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const start = Io.Timestamp.now(io, .awake);
var a = io.async(fetch, .{ io, "weather", 600 });
defer _ = a.cancel(io) catch {};
var b = io.async(fetch, .{ io, "news", 400 });
defer _ = b.cancel(io) catch {};
const first = try a.await(io);
const second = try b.await(io);
const ms = start.untilNow(io, .awake).toMilliseconds();
std.debug.print("got {s} and {s}\n", .{ first, second });
std.debug.print("took about {d} ms\n", .{@divTrunc(ms, 100) * 100});
}

Output:

got weather and news
took about 600 ms

600 ms and 400 ms, but the whole thing took about 600 ms, not 1000. Both fetches were waiting at the same time. Let’s go through the new parts:

  1. io.async(fetch, .{ io, "weather", 600 }) starts fetch with those arguments. The function is a completely normal function; the arguments go in a tuple, like std.debug.print’s.
  2. It returns right away with a Future: a handle to a result that may not exist yet. Its result type is whatever fetch returns, here an error union holding a []const u8.
  3. a.await(io) waits until that task is done and gives you its return value, error included, so you use try on it.
  4. defer _ = a.cancel(io) catch {}; is the cleanup line. More on that below; for now, write it right after every io.async.

async means “may run at the same time”, not “will”

Section titled “async means “may run at the same time”, not “will””

Here’s a detail that surprises people. io.async tells Zig that a call is independent: it’s okay to run it alongside other work. It doesn’t promise that it will. If the io has no way to run things in parallel, it simply calls the function on the spot.

You can see it by swapping in a single-threaded io:

const std = @import("std");
const Io = std.Io;
fn fetch(io: Io, name: []const u8, ms: i64) ![]const u8 {
std.debug.print("start {s}\n", .{name});
try io.sleep(.fromMilliseconds(ms), .awake);
std.debug.print("done {s}\n", .{name});
return name;
}
pub fn main() !void {
var threaded: Io.Threaded = .init_single_threaded;
const io = threaded.io();
const start = Io.Timestamp.now(io, .awake);
var a = io.async(fetch, .{ io, "weather", 600 });
defer _ = a.cancel(io) catch {};
var b = io.async(fetch, .{ io, "news", 400 });
defer _ = b.cancel(io) catch {};
_ = try a.await(io);
_ = try b.await(io);
const ms = start.untilNow(io, .awake).toMilliseconds();
std.debug.print("took about {d} ms\n", .{@divTrunc(ms, 100) * 100});
}

Output:

start weather
done weather
start news
done news
took about 1000 ms

Same code, no parallelism: each io.async ran its function to the end before returning, so the total is 600 + 400. The program is still correct, just slower. That’s the deal async makes: your code works with any io, and gets faster when the io can do more. The default init.io uses a pool of threads, and when every thread is busy it also falls back to running the task right away.

A task’s error doesn’t disappear. It comes back when you await:

const std = @import("std");
const Io = std.Io;
fn check(io: Io, id: u32) !void {
try io.sleep(.fromMilliseconds(100 * id), .awake);
if (id == 2) return error.BadInput;
std.debug.print("task {d} ok\n", .{id});
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var one = io.async(check, .{ io, 1 });
defer one.cancel(io) catch {};
var two = io.async(check, .{ io, 2 });
defer two.cancel(io) catch {};
var three = io.async(check, .{ io, 3 });
defer three.cancel(io) catch {};
try one.await(io);
two.await(io) catch |err| std.debug.print("task 2 failed: {t}\n", .{err});
try three.await(io);
}

Output:

task 1 ok
task 2 failed: BadInput
task 3 ok

You handle a task’s error exactly like a normal call’s: try, catch, or a switch on it. (These tasks return !void, so there’s no value to discard, and the cleanup line loses its _ =.)

Sometimes you stop caring about a task: the user gave up, another task already found the answer, or something else failed. future.cancel(io) asks the task to stop and then waits for it, just like await:

const std = @import("std");
const Io = std.Io;
fn slowDownload(io: Io) ![]const u8 {
try io.sleep(.fromSeconds(10), .awake);
return "big file";
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var download = io.async(slowDownload, .{io});
try io.sleep(.fromMilliseconds(200), .awake);
std.debug.print("taking too long, canceling\n", .{});
if (download.cancel(io)) |data| {
std.debug.print("finished anyway: {s}\n", .{data});
} else |err| {
std.debug.print("download stopped: {t}\n", .{err});
}
}

Output:

taking too long, canceling
download stopped: Canceled

The program ends after about 200 ms, not 10 seconds. Canceling works by making the task’s next I/O call (here, the sleep) return error.Canceled. Most I/O functions in Zig 0.17 have it in their error set, and plain try passes it up, so most tasks need no extra code to be cancelable. A task that’s busy computing and never does I/O can call try io.checkCancel() now and then to notice a cancel request.

Notice the if ... else |err|: a cancel can still return a real result, because the task might have finished just before you asked. That’s why the 0.16.0 release notes on futures recommend this pattern after every io.async:

var task = io.async(work, .{io});
defer _ = task.cancel(io) catch {};

await and cancel are both idempotent: once one of them has run, the other just returns the same result. So this defer does nothing on the happy path (you already awaited), but if your function leaves early because of a try somewhere, it stops the task and frees what it used.

Keeping one variable per future gets clumsy with ten or a hundred tasks. A std.Io.Group holds any number of them, and you wait for all of them together:

const std = @import("std");
const Io = std.Io;
fn countWords(io: Io, text: []const u8, out: *usize) Io.Cancelable!void {
try io.sleep(.fromMilliseconds(100), .awake); // pretend this is slow
var it = std.mem.tokenizeScalar(u8, text, ' ');
var n: usize = 0;
while (it.next()) |_| n += 1;
out.* = n;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const pages = [_][]const u8{
"the quick brown fox",
"jumps over",
"the lazy dog again and again",
};
var counts: [pages.len]usize = undefined;
var group: Io.Group = .init;
defer group.cancel(io);
for (pages, &counts) |page, *slot| {
group.async(io, countWords, .{ io, page, slot });
}
try group.await(io);
for (pages, counts) |page, n| std.debug.print("{d} words: {s}\n", .{ n, page });
}

Output:

4 words: the quick brown fox
2 words: jumps over
6 words: the lazy dog again and again

A few things to notice:

  • group.async(io, function, args) returns nothing. Tasks in a group can’t hand back values, so each one writes its answer through a pointer, here into its own slot in counts.
  • The task function must return void or Io.Cancelable!void (an error set with only error.Canceled). Errors other than that have to be handled inside the task.
  • group.await(io) waits for all of them. defer group.cancel(io) is the same safety net as before.

Each task writes to a different slot, so they never touch the same memory. If they all updated one shared counter, you’d need the tools in Zig Mutexes & Atomics.

So far, running tasks one after another would have been slower but still correct. Sometimes it isn’t. Here’s a producer that puts numbers into a small queue and a consumer that takes them out:

const std = @import("std");
const Io = std.Io;
fn producer(io: Io, queue: *Io.Queue(u32)) !void {
for (1..6) |n| {
try queue.putOne(io, @intCast(n));
std.debug.print("sent {d}\n", .{n});
}
queue.close(io);
}
fn consumer(io: Io, queue: *Io.Queue(u32)) !u32 {
var total: u32 = 0;
while (true) {
const n = queue.getOne(io) catch |err| switch (err) {
error.Closed => return total,
else => |e| return e,
};
total += n;
}
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var buffer: [2]u32 = undefined;
var queue: Io.Queue(u32) = .init(&buffer);
var prod = try io.concurrent(producer, .{ io, &queue });
defer prod.cancel(io) catch {};
var cons = try io.concurrent(consumer, .{ io, &queue });
defer _ = cons.cancel(io) catch {};
try prod.await(io);
const total = try cons.await(io);
std.debug.print("total: {d}\n", .{total});
}

Output:

sent 1
sent 2
sent 3
sent 4
sent 5
total: 15

The queue only holds 2 numbers. When it’s full, putOne waits until the consumer takes one out. That only works if the consumer is really running at the same time. If the producer ran first, on its own, it would fill the queue and wait forever for a consumer that never starts.

That’s the difference:

  • io.async: “this can run alongside other work”. Always succeeds; may just run the function immediately.
  • io.concurrent: “this must run alongside other work, or my program is wrong”. If the io can’t do that, it fails with error.ConcurrencyUnavailable instead of hanging.

With the single-threaded io from earlier, io.concurrent fails straight away:

const std = @import("std");
const Io = std.Io;
fn work(io: Io) !void {
try io.sleep(.fromMilliseconds(10), .awake);
}
pub fn main() !void {
var threaded: Io.Threaded = .init_single_threaded;
const io = threaded.io();
var task = io.concurrent(work, .{io}) catch |err| {
std.debug.print("concurrent failed: {t}\n", .{err});
return;
};
try task.await(io);
}

Output:

concurrent failed: ConcurrencyUnavailable

And if you change the queue program to use io.async with that single-threaded io, it prints sent 1 and sent 2, then hangs forever. An error is much better than a hang, which is why concurrent exists.

With the default init.io, async tasks do run on real operating system threads from a pool, so a task that does heavy computing really does run on another CPU core. The difference from Zig Threads is who’s in charge: with std.Thread you create and join threads yourself, while with io.async you describe independent work and let the io decide how to run it. Tasks still share memory, so the same rules about shared data apply.

Start three tasks with io.async that sleep 300, 200 and 100 ms and then return their sleep time. Await them all and print the sum of the returned numbers.

Hint: fn nap(io: Io, ms: i64) !i64 { try io.sleep(.fromMilliseconds(ms), .awake); return ms; }

Show solution
const std = @import("std");
const Io = std.Io;
fn nap(io: Io, ms: i64) !i64 {
try io.sleep(.fromMilliseconds(ms), .awake);
return ms;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var a = io.async(nap, .{ io, 300 });
defer _ = a.cancel(io) catch {};
var b = io.async(nap, .{ io, 200 });
defer _ = b.cancel(io) catch {};
var c = io.async(nap, .{ io, 100 });
defer _ = c.cancel(io) catch {};
const total = try a.await(io) + try b.await(io) + try c.await(io);
std.debug.print("slept {d} ms in total, but only waited about 300\n", .{total});
}

Output:

slept 600 ms in total, but only waited about 300

The three naps overlap, so the program finishes after about 300 ms even though the naps add up to 600.

Use an Io.Group to compute the squares of 1 to 5 in separate tasks, each writing into its own slot of an array, then print the array.

Hint: the task function returns Io.Cancelable!void and takes a *u64 for its answer. Loop with for (&results, 1..) |*slot, n|.

Show solution
const std = @import("std");
const Io = std.Io;
fn square(n: u64, out: *u64) Io.Cancelable!void {
out.* = n * n;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var results: [5]u64 = undefined;
var group: Io.Group = .init;
defer group.cancel(io);
for (&results, 1..) |*slot, n| group.async(io, square, .{ n, slot });
try group.await(io);
std.debug.print("{any}\n", .{results});
}

Output:

{ 1, 4, 9, 16, 25 }

square doesn’t even take io: any function can be a task. Each task has its own slot, so no locking is needed.

Start a task that sleeps for 5 seconds. After 100 ms, cancel it and print what cancel returned.

Hint: use if (task.cancel(io)) |_| ... else |err| ....

Show solution
const std = @import("std");
const Io = std.Io;
fn longJob(io: Io) !void {
try io.sleep(.fromSeconds(5), .awake);
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var task = io.async(longJob, .{io});
try io.sleep(.fromMilliseconds(100), .awake);
if (task.cancel(io)) |_| {
std.debug.print("it finished\n", .{});
} else |err| {
std.debug.print("gave up: {t}\n", .{err});
}
}

Output:

gave up: Canceled

The sleep inside longJob returned error.Canceled, try passed it up, and cancel handed it to us.

  • io.async(function, .{args}) starts a normal function as an independent task and returns a Future.
  • future.await(io) waits and returns the function’s result, errors included.
  • future.cancel(io) requests a stop (the task’s next I/O call returns error.Canceled) and then waits.
  • Write defer _ = task.cancel(io) catch {}; after every io.async; forgetting both await and cancel leaks.
  • std.Io.Group runs many tasks with one await; tasks return Io.Cancelable!void and write results through pointers.
  • io.async may run the task immediately; io.concurrent guarantees real concurrency or fails with error.ConcurrencyUnavailable.

Next up: Zig Threads, creating and joining operating system threads yourself with std.Thread.

Quick check

1. What does io.async(fetch, .{ io, "x" }) return?
2. With a single-threaded io, what does io.async do?
3. A producer and a consumer share a small queue and wait on each other. Which should you use?
4. Why write defer _ = task.cancel(io) catch {}; right after io.async?