Async Functions
An async function is a function whose callsite is split into an 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.
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
$ zig test test.zig
1/1 test "suspend with no resume"...OK
All 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 tests passed.
suspend
causes a function to be async
.
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
$ zig test test.zig
1/1 test "resume from suspend"...OK
All tests passed.
This is guaranteed to tail call, and therefore will not cause a new stack frame.
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();
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 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 implicitly casts to anyframe->T
.
test.zig
$ zig test test.zig
1/1 test "async function await"...OK
All 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.
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.direct_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 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
$ zig build-exe blocking.zig
$ ./blocking
fetchUrl returning
readFile returning
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.