Async Functions
When a function is called, a frame is pushed to the stack, the function runs until it reaches a return statement, and then the frame is popped from the stack. At the callsite, the following code does not run until the function returns.
An async function is a function whose callsite is split into an async
initiation, followed by an await
completion. Its frame is provided explicitly by the caller, and it can be suspended and resumed any number of times.
Zig infers that a function is async
when it observes that the function contains a suspension point. Async functions can be called the same as normal functions. A function call of an async function is a suspend point.
Suspend and Resume
At any point, a function may suspend itself. This causes control flow to return to the callsite (in the case of the first suspension), or resumer (in the case of subsequent suspensions).
test.zig
const std = @import("std");
const assert = std.debug.assert;
var x: i32 = 1;
test "suspend with no resume" {
var frame = async func();
assert(x == 2);
}
fn func() void {
x += 1;
suspend;
// This line is never reached because the suspend has no matching resume.
x += 1;
}
$ zig test test.zig
1/1 test "suspend with no resume"...OK
All 1 tests passed.
In the same way that each allocation should have a corresponding free, Each suspend
should have a corresponding resume
. A suspend block allows a function to put a pointer to its own frame somewhere, for example into an event loop, even if that action will perform a resume
operation on a different thread. @frame provides access to the async function frame pointer.
test.zig
const std = @import("std");
const assert = std.debug.assert;
var the_frame: anyframe = undefined;
var result = false;
test "async function suspend with block" {
_ = async testSuspendBlock();
assert(!result);
resume the_frame;
assert(result);
}
fn testSuspendBlock() void {
suspend {
comptime assert(@TypeOf(@frame()) == *@Frame(testSuspendBlock));
the_frame = @frame();
}
result = true;
}
$ zig test test.zig
1/1 test "async function suspend with block"...OK
All 1 tests passed.
suspend
causes a function to be async
.
Resuming from Suspend Blocks
Upon entering a suspend
block, the async function is already considered suspended, and can be resumed. For example, if you started another kernel thread, and had that thread call resume
on the frame pointer provided by the @frame, the new thread would begin executing after the suspend block, while the old thread continued executing the suspend block.
However, the async function can be directly resumed from the suspend block, in which case it never returns to its resumer and continues executing.
test.zig
const std = @import("std");
const assert = std.debug.assert;
test "resume from suspend" {
var my_result: i32 = 1;
_ = async testResumeFromSuspend(&my_result);
std.debug.assert(my_result == 2);
}
fn testResumeFromSuspend(my_result: *i32) void {
suspend {
resume @frame();
}
my_result.* += 1;
suspend;
my_result.* += 1;
}
$ zig test test.zig
1/1 test "resume from suspend"...OK
All 1 tests passed.
This is guaranteed to tail call, and therefore will not cause a new stack frame.
Async and Await
In the same way that every suspend
has a matching resume
, every async
has a matching await
.
test.zig
const std = @import("std");
const assert = std.debug.assert;
test "async and await" {
// Here we have an exception where we do not match an async
// with an await. The test block is not async and so cannot
// have a suspend point in it.
// This is well-defined behavior, and everything is OK here.
// Note however that there would be no way to collect the
// return value of amain, if it were something other than void.
_ = async amain();
}
fn amain() void {
var frame = async func();
comptime assert(@TypeOf(frame) == @Frame(func));
const ptr: anyframe->void = &frame;
const any_ptr: anyframe = ptr;
resume any_ptr;
await ptr;
}
fn func() void {
suspend;
}
$ zig test test.zig
1/1 test "async and await"...OK
All 1 tests passed.
The await
keyword is used to coordinate with an async function's return
statement.
await
is a suspend point, and takes as an operand anything that coerces to anyframe->T
.
There is a common misconception that await
resumes the target function. It is the other way around: it suspends until the target function completes. In the event that the target function has already completed, await
does not suspend; instead it copies the return value directly from the target function's frame.
test.zig
const std = @import("std");
const assert = std.debug.assert;
var the_frame: anyframe = undefined;
var final_result: i32 = 0;
test "async function await" {
seq('a');
_ = async amain();
seq('f');
resume the_frame;
seq('i');
assert(final_result == 1234);
assert(std.mem.eql(u8, &seq_points, "abcdefghi"));
}
fn amain() void {
seq('b');
var f = async another();
seq('e');
final_result = await f;
seq('h');
}
fn another() i32 {
seq('c');
suspend {
seq('d');
the_frame = @frame();
}
seq('g');
return 1234;
}
var seq_points = [_]u8{0} ** "abcdefghi".len;
var seq_index: usize = 0;
fn seq(c: u8) void {
seq_points[seq_index] = c;
seq_index += 1;
}
$ zig test test.zig
1/1 test "async function await"...OK
All 1 tests passed.
In general, suspend
is lower level than await
. Most application code will use only async
and await
, but event loop implementations will make use of suspend
internally.
Async Function Example
Putting all of this together, here is an example of typical async
/await
usage:
async.zig
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn main() void {
_ = async amainWrap();
// Typically we would use an event loop to manage resuming async functions,
// but in this example we hard code what the event loop would do,
// to make things deterministic.
resume global_file_frame;
resume global_download_frame;
}
fn amainWrap() void {
amain() catch |e| {
std.debug.warn("{}\n", .{e});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
std.process.exit(1);
};
}
fn amain() !void {
const allocator = std.heap.page_allocator;
var download_frame = async fetchUrl(allocator, "https://example.com/");
var awaited_download_frame = false;
errdefer if (!awaited_download_frame) {
if (await download_frame) |r| allocator.free(r) else |_| {}
};
var file_frame = async readFile(allocator, "something.txt");
var awaited_file_frame = false;
errdefer if (!awaited_file_frame) {
if (await file_frame) |r| allocator.free(r) else |_| {}
};
awaited_file_frame = true;
const file_text = try await file_frame;
defer allocator.free(file_text);
awaited_download_frame = true;
const download_text = try await download_frame;
defer allocator.free(download_text);
std.debug.warn("download_text: {}\n", .{download_text});
std.debug.warn("file_text: {}\n", .{file_text});
}
var global_download_frame: anyframe = undefined;
fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the downloaded url contents");
errdefer allocator.free(result);
suspend {
global_download_frame = @frame();
}
std.debug.warn("fetchUrl returning\n", .{});
return result;
}
var global_file_frame: anyframe = undefined;
fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the file contents");
errdefer allocator.free(result);
suspend {
global_file_frame = @frame();
}
std.debug.warn("readFile returning\n", .{});
return result;
}
$ zig build-exe async.zig
$ ./async
readFile returning
fetchUrl returning
download_text: this is the downloaded url contents
file_text: this is the file contents
Now we remove the suspend
and resume
code, and observe the same behavior, with one tiny difference:
blocking.zig
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn main() void {
_ = async amainWrap();
}
fn amainWrap() void {
amain() catch |e| {
std.debug.warn("{}\n", .{e});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
std.process.exit(1);
};
}
fn amain() !void {
const allocator = std.heap.page_allocator;
var download_frame = async fetchUrl(allocator, "https://example.com/");
var awaited_download_frame = false;
errdefer if (!awaited_download_frame) {
if (await download_frame) |r| allocator.free(r) else |_| {}
};
var file_frame = async readFile(allocator, "something.txt");
var awaited_file_frame = false;
errdefer if (!awaited_file_frame) {
if (await file_frame) |r| allocator.free(r) else |_| {}
};
awaited_file_frame = true;
const file_text = try await file_frame;
defer allocator.free(file_text);
awaited_download_frame = true;
const download_text = try await download_frame;
defer allocator.free(download_text);
std.debug.warn("download_text: {}\n", .{download_text});
std.debug.warn("file_text: {}\n", .{file_text});
}
fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the downloaded url contents");
errdefer allocator.free(result);
std.debug.warn("fetchUrl returning\n", .{});
return result;
}
fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the file contents");
errdefer allocator.free(result);
std.debug.warn("readFile returning\n", .{});
return result;
}
$ zig build-exe blocking.zig
$ ./blocking
fetchUrl returning
readFile returning
download_text: this is the downloaded url contents
file_text: this is the file contents
Previously, the fetchUrl
and readFile
functions suspended, and were resumed in an order determined by the main
function. Now, since there are no suspend points, the order of the printed "… returning" messages is determined by the order of async
callsites.