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. The code following the callsite does not run until the function returns.
An async function is a function whose execution 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.
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.
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).
suspend_no_resume.zig
const std = @import("std");
const expect = std.testing.expect;
var x: i32 = 1;
test "suspend with no resume" {
var frame = async func();
try expect(x == 2);
_ = frame;
}
fn func() void {
x += 1;
suspend {}
// This line is never reached because the suspend has no matching resume.
x += 1;
}
Shell
$ zig test suspend_no_resume.zig -fstage1
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.
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 -fstage1
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.
resume_from_suspend.zig
const std = @import("std");
const expect = std.testing.expect;
test "resume from suspend" {
var my_result: i32 = 1;
_ = async testResumeFromSuspend(&my_result);
try std.testing.expect(my_result == 2);
}
fn testResumeFromSuspend(my_result: *i32) void {
suspend {
resume @frame();
}
my_result.* += 1;
suspend {}
my_result.* += 1;
}
Shell
$ zig test resume_from_suspend.zig -fstage1
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
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 {
var frame = async func();
comptime try expect(@TypeOf(frame) == @Frame(func));
const ptr: anyframe->void = &frame;
const any_ptr: anyframe = ptr;
resume any_ptr;
await ptr;
}
fn func() void {
suspend {}
}
Shell
$ zig test async_await.zig -fstage1
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.
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.
async_await_sequence.zig
const std = @import("std");
const expect = std.testing.expect;
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');
try expect(final_result == 1234);
try expect(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;
}
Shell
$ zig test async_await_sequence.zig -fstage1
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.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) {
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.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 -fstage1
$ ./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.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) {
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.print("download_text: {s}\n", .{download_text});
std.debug.print("file_text: {s}\n", .{file_text});
}
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);
std.debug.print("fetchUrl returning\n", .{});
return result;
}
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);
std.debug.print("readFile returning\n", .{});
return result;
}
Shell
$ zig build-exe blocking.zig -fstage1
$ ./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.