2. Async functions
The task of step 1 contains the same code twice, once for each neighbor. This step moves that code into a function. The program of this step is in website/examples/tutorial/2-await.
Declaring an async function
Section titled “Declaring an async function”A function that contains suspend is declared with async fn:
// Receives one value from in and returns it.async fn receive(comptime in: fabin_dsd) f32 { var value: f32 = 0.0; const value_dsd = @get_dsd(mem1d_dsd, .{ .base_address = &value, .extent = 1 }); @fmovs(value_dsd, in, .{ .async = true, .activate = @current_task() }); suspend; // continues here when the value has arrived return value;}An async function has parameters and a return value like any function. receive takes the fabric input DSD to receive from and returns the value that it received. The DSD is a comptime parameter, so it is not passed at runtime. value is a local variable of the function. Like the local variables of an async task, it keeps its value and its address while the function is suspended.
Calling it with @await
Section titled “Calling it with @await”An async function is called with @await:
async task sum_task() void { const west = @await(receive(west_in_dsd)); const east = @await(receive(east_in_dsd)); x[0] = west + east; sys_mod.unblock_cmd_stream();}@await(receive(west_in_dsd)) calls receive and returns its result when receive has returned. In between, receive suspends: the run of the task ends inside receive. When the receive operation activates the task, the task continues inside receive, which then returns to sum_task.
The second call starts when the first one has returned. The task still receives the two values one after the other, as in step 1.
@await is an expression. The task can also be written without the two constants:
x[0] = @await(receive(west_in_dsd)) + @await(receive(east_in_dsd));Awaited functions run on the caller’s task
Section titled “Awaited functions run on the caller’s task”receive does not have a task of its own. A function that is called with @await runs on the task of its caller, like an ordinary function call:
@current_task()inreceiveis the ID ofsum_task. The receive operation therefore activatessum_task, andsum_taskcontinues insidereceive.- The local variables of
receiveare on the stack ofsum_task.
@await therefore needs no task ID and no memory beyond the stack frame of the function.
- An async function can only be called from an async function or an async task, and only as the argument of
@awaitor@await_parallel.receive(west_in_dsd)without@awaitis an error. - An async function can call ordinary functions and can await other async functions. An
@awaitcan stand in a loop or in a branch, like any call. suspendis only allowed in async functions and async tasks.
Async functions and tasks and Calling async functions are the reference.
The program still chooses its colors, its queues and its task ID by number. The next step changes that.