Project: concurrency by hand
Before letting a macro rewrite your code, do the rewrite yourself once. This chapter builds a small program three ways:
- as written, one
awaitafter another; - concurrently, by hand, with nothing but
std; - with
#[psync::graph], which writes version 2 for you.
You will need no compiler knowledge. By the end you will know what psync generates, why it is
safe, and how to read the graph it prints. The whole program is
examples/by_hand.rs
in the repository. Run it as you read:
cargo run --example by_hand --no-default-features
A future is a value you poll
An async fn does not run when you call it. It returns a future: a value with one method,
poll. Each poll runs the function until it reaches an .await on something that is not ready
yet. Then poll returns Poll::Pending, and the future remembers where it stopped. Polled again
later, it carries on from there. When the function returns, poll returns Poll::Ready(value).
Who calls poll? An executor. Here is a complete one, in ten lines:
struct Unpark(Thread);
impl Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let waker = Arc::new(Unpark(thread::current())).into();
let mut cx = Context::from_waker(&waker);
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
thread::park();
}
}
block_on polls the future. If the future is not ready, the thread sleeps (park) until someone
calls the waker it handed over in the Context. The waker unparks the thread, and the loop
polls again.
The other half is a future that is actually waiting for something. Real programs wait for the network. Ours waits for a timer: a helper thread sleeps, then calls the waker, as a network driver would when a reply arrives.
async fn sleep_ms(ms: u64) {
let mut deadline = None;
poll_fn(|cx| {
let at = *deadline.get_or_insert_with(|| {
let waker = cx.waker().clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(ms));
waker.wake();
});
Instant::now() + Duration::from_millis(ms)
});
if Instant::now() >= at { Poll::Ready(()) } else { Poll::Pending }
})
.await
}
poll_fn turns a closure into a future: each poll calls the closure. This one starts the timer
on its first poll and is ready once the deadline has passed.
That is a whole async runtime. Tokio and embassy do the same with better timers and many tasks.
Version 1: as written
The program is a client for a remote API. Each call takes 100 ms:
#[psync::graph(off)]
async fn profile_page_sequential(api: &Api, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
let friends = api.friends(user_id).await?;
Ok(Page { user, posts, avatar, friends })
}
(#[psync::graph(off)] leaves the function exactly as written. It is here so the file can
hold all three versions.)
Each .await waits for its call to finish before the next line starts, so the function takes
four round trips: about 400 ms. Yet only one line needs an earlier one. avatar reads
user.avatar_url, so it must wait for user. posts and friends need only user_id, which
we had from the start.
Drawing the graph
Write each statement as a box, and draw an arrow from a statement to every later statement that reads what it wrote:
profile_page. One arrow: avatar reads user.Every path through the graph is a chain: statements that must run in order. There are three
chains, user → avatar, posts and friends, and nothing connects them. Run the three chains at
the same time and the function takes as long as the longest chain: two round trips, about
200 ms.
Version 2: by hand
First, the chains. An async block is a future too, and like an async fn it does nothing until
it is polled. So writing the chains down does not start anything yet:
let chain0 = async {
let user = api.user(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
Ok::<_, Error>((user, avatar))
};
let chain1 = async { api.posts(user_id).await };
let chain2 = async { api.friends(user_id).await };
The ? inside an async block returns from the block, not from the function. So an error in
chain0 stops chain0 and becomes its output. The other chains carry on.
Next, the join: one future that polls all three chains, keeps each output as it arrives, and is ready when all three are.
let (mut f0, mut f1, mut f2) = (pin!(chain0), pin!(chain1), pin!(chain2));
let (mut out0, mut out1, mut out2) = (None, None, None);
poll_fn(|cx| {
if out0.is_none() && let Poll::Ready(v) = f0.as_mut().poll(cx) {
out0 = Some(v);
}
if out1.is_none() && let Poll::Ready(v) = f1.as_mut().poll(cx) {
out1 = Some(v);
}
if out2.is_none() && let Poll::Ready(v) = f2.as_mut().poll(cx) {
out2 = Some(v);
}
if out0.is_some() && out1.is_some() && out2.is_some() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
The first poll of the join starts all three chains: each runs until its first .await and starts
its timer. All three timers now run at once. Each timer wakes the same task when it fires, the
join is polled again, and it polls the chains that have not finished.
Notice what this needs: no threads for the chains, no Send, no 'static, no spawn. The chains
borrow api and user_id from the function, and that is fine, because they all live inside the
function’s own future. That is why psync works on any executor, including on a microcontroller.
Last, put the results back together. The original function returned the first error in source
order: if api.user failed, it never even called api.posts. The concurrent version may see
several errors at once, so it raises them in the original order:
let (user, avatar) = out0.expect("joined")?;
let posts = out1.expect("joined")?;
let friends = out2.expect("joined")?;
Ok(Page { user, posts, avatar, friends })
user’s error is on the first line, so it wins over posts’s on the second, as before.
One thing did change. If
api.userfails, version 1 never callsapi.posts. Version 2 has already sent it. For a read that is harmless. For a write, such as “charge the card”, it is not, and psync must not move it ahead of a check it used to wait for. Early exits and errors and Side effects explain how psync decides, and how you tell it.
Version 3: the macro
Now put the attribute on the original function, and ask it to explain itself:
#[psync::graph(explain)]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
let friends = api.friends(user_id).await?;
Ok(Page { user, posts, avatar, friends })
}
psync::graph `profile_page`:
region 0:
n0: user = user()? [await]
n1: posts = posts()? [await]
n2: avatar = avatar()? [await]
n3: friends = friends()? [await]
n0 -> n2 (reads `user`)
level 0: n0->n2 || n1 || n3
unclassified (assumed to read; `strict` treats them as writes): user, posts, avatar, friends
Read it against your drawing:
n0…n3are the statements, in source order.?marks an early exit and[await]an await.n0 -> n2 (readsuser)is the arrow you drew.level 0: …is the schedule.->joins the statements of one chain, and||separates chains that run at the same time: yourchain0,chain1andchain2.- The last line is psync being honest. It knows many library calls (
reqwest,tokio::fs,std::process, …) and what they touch outside the program. YourApimethods are not among them, so psync assumes they only read, and says so. Ifapi.postswrote something thatapi.userread, that assumption would be wrong. Hints and Side effects show how to tell psync, andstrictmakes it treat every unknown call as a write.
Generated code shows the code behind this report, and it is version 2:
an async block per chain, a poll_fn join, and the errors re-raised in source order. The only
differences are names and bookkeeping (it also handles return, break and continue in a
chain).
Run it
sequential 401 ms
by hand 200 ms
psync 200 ms
all three pages are equal
Same pages, half the time, and the third version is the code you started with.
Quiz
? You call `profile_page(&api, 7)` and drop the result without awaiting it. How many requests reach the server?
+ None
- One, `api.user`
- All four, concurrently
> Calling an `async fn` only builds a future. Nothing runs until something polls it.
? A future's `poll` returns `Poll::Pending`. What has it promised?
- To be ready on the next poll
+ To make sure its waker is called when polling it again is worth it
- To block the thread until it is ready
> `Pending` hands the job back to the executor. The future (or what it waits on) keeps the waker and calls it when there is progress to make; `block_on` parks until then.
? Which statements of `profile_page` share a chain?
+ `user` and `avatar`
- `user` and `posts`
- `posts` and `friends`
- All four
> `avatar` reads `user.avatar_url`. Nothing else reads anything an earlier statement wrote.
? Both `api.user` and `api.posts` fail. The posts error arrives first. Which error does the by-hand version return?
+ The user error
- The posts error
- Whichever arrived first, so it varies
> Errors are re-raised in source order, so the result does not depend on timing and matches the sequential version.
? Why can the chains borrow `api` without `Arc` or `'static`?
- psync clones `api` into each chain
+ The chains are polled inside the function's own future, on the same task, so the borrow outlives them
- `Api` is `Copy`
> Nothing is spawned. The join is an ordinary future that lives in the function's frame, so normal borrowing works. This is why psync runs on any executor.
Exercises
- Change
friendstoapi.friends(user.id), after givingUseranidfield. Draw the new graph. How long does the function take now? What doesexplainprint? - Swap the first two lines of
profile_page. Does the schedule change? Does the result? - In version 2, delete the
out0.is_none() &&test, so the join pollschain0again after it finished. What happens, and why does Rust allow you to write it? - Make
api.postsreturn an error andapi.usertoo. Which error does each version return? Why must version 2 not simply return the first error that arrives? - Our
sleep_msspawns a thread per call. Why would a real runtime not do that, and why does it not matter for what this chapter measures?
Answers
-
Now
friendsreadsusertoo, so the graph has two arrows out ofn0.usercannot sit in two chains, so psync splits the work into two levels:userandpostsfirst, thenavatarandfriends. Still two round trips, about 200 ms:n0 -> n2 (reads `user`) n0 -> n3 (reads `user`) level 0: n0 || n1 level 1: n2 || n3Basic concepts explains levels, and when they cost time.
-
No and no. The graph has the same arrow, so the chains are the same. psync numbers statements in source order, so the names change:
level 0: n0 || n1->n2 || n3. -
Polling a future after it returned
Readyis a logic error. Anasyncblock panics with"`async fn` resumed after completion". The compiler allows the call becausepollis an ordinary method; the “never poll again” rule is part of theFuturecontract, not of the type system. psync’s join keeps aMaybeDoneper chain for exactly this reason. -
Both return
user’s error. Version 1 stops at the first line. Version 2 gets both errors, but raises them in source order. Returning whichever arrived first would make the result depend on the network’s timing: a different error on each run. -
Threads cost memory and a system call each; a real timer keeps one sorted queue of deadlines (see
examples/graph_suite/runtime.rs). Here we measure how many round trips the function waits for, and a sleeping thread waits exactly as long as a queued deadline.