Async Functions
An async function is a function whose execution 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.
The code following the async
callsite runs immediately after the async function first suspends. When the return value of the async function is needed, the calling code can await
on the async function frame. This will suspend the calling code until the async function completes, at which point execution resumes just after the await
callsite.
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).
suspend_no_resume.zig
Shell
$ zig test suspend_no_resume.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. provides access to the async function frame pointer.
async_suspend_block.zig
const std = @import("std");
const expect = std.testing.expect;
var the_frame: anyframe = undefined;
var result = false;
test "async function suspend with block" {
_ = async testSuspendBlock();
try expect(!result);
resume the_frame;
try expect(result);
}
fn testSuspendBlock() void {
suspend {
comptime try expect(@TypeOf(@frame()) == *@Frame(testSuspendBlock));
the_frame = @frame();
}
result = true;
}
Shell
$ zig test async_suspend_block.zig
1/1 test "async function suspend with block"... OK
All 1 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.
resume_from_suspend.zig
Shell
$ zig test resume_from_suspend.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.
In the same way that every suspend
has a matching resume
, every async
has a matching await
in standard code.
However, it is possible to have an async
call without a matching await
. Upon completion of the async function, execution would continue at the most recent async
callsite or resume
callsite, and the return value of the async function would be lost.
async_await.zig
const std = @import("std");
const expect = std.testing.expect;
test "async and await" {
// The test block is not async and so cannot have a suspend
// point in it. By using the nosuspend keyword, we promise that
// the code in amain will finish executing without suspending
// back to the test block.
nosuspend amain();
}
fn amain() void {
comptime try expect(@TypeOf(frame) == @Frame(func));
const ptr: anyframe->void = &frame;
resume any_ptr;
await ptr;
}
fn func() void {
suspend {}
}
Shell
$ zig test async_await.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
. Calling await
on the frame of an async function will cause execution to continue at the await
callsite once the target function completes.
async_await_sequence.zig
Shell
$ zig test async_await_sequence.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.
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.print("{}\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) {
};
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.print("download_text: {s}\n", .{download_text});
std.debug.print("file_text: {s}\n", .{file_text});
}
var global_download_frame: anyframe = undefined;
fn fetchUrl(allocator: Allocator, url: []const u8) ![]u8 {
_ = url; // this is just an example, we don't actually do it!
const result = try allocator.dupe(u8, "this is the downloaded url contents");
errdefer allocator.free(result);
suspend {
global_download_frame = @frame();
}
std.debug.print("fetchUrl returning\n", .{});
return result;
}
var global_file_frame: anyframe = undefined;
fn readFile(allocator: Allocator, filename: []const u8) ![]u8 {
_ = filename; // this is just an example, we don't actually do it!
const result = try allocator.dupe(u8, "this is the file contents");
errdefer allocator.free(result);
suspend {
global_file_frame = @frame();
}
std.debug.print("readFile returning\n", .{});
return result;
}
Shell
$ 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
Shell
$ zig build-exe blocking.zig
$ ./blocking
fetchUrl returning
readFile returning
download_text: this is the downloaded url contents
Previously, the fetchUrl
and readFile
functions suspended, and were resumed in an order determined by the function. Now, since there are no suspend points, the order of the printed “… returning” messages is determined by the order of async
callsites.