Skip to content

Commit

Permalink
explain earlier line (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
carllerche committed Jul 14, 2020
1 parent 5f92327 commit 6b79142
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions content/tokio/tutorial/async.md
Original file line number Diff line number Diff line change
Expand Up @@ -361,12 +361,45 @@ fix them later.

[[warning]]
| When a future returns `Poll::Pending`, it **must** ensure that the waker is
| signalled at some point in the future. Forgetting to do this results
| in the task hanging indefinitely.
| signalled at some point. Forgetting to do this results in the task hanging
| indefinitely.
|
| Forgetting to wake a task after returning `Poll::Pending` is a common
| source of bugs.

Recall the first iteration of `Delay`. Here was the future implementation:

```rust
impl Future for Delay {
type Output = &'static str;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<&'static str>
{
if Instant::now() >= self.when {
println!("Hello world");
Poll::Ready("done")
} else {
// Ignore this line for now.
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
```

Before returning `Poll::Pending`, we called `cx.waker().wake_by_ref()`. This is
to satisfy the future contract. By returning `Poll::Pending`, we are responsible
for signalling the waker. Because we didn't implement the timer thread yet, we
signalled the waker inline. Doing so will result in the future being immediately
re-scheduled, executed again, and probably not be ready to complete.

Notice that you are allowed to signal the waker more often than necessary. In
this particular case, we signal the waker even though we are not ready to
continue the operation at all. There is nothing wrong with this besides some
wasted CPU cycles, however, this particular implementation will result in a busy
loop.

## Updating Mini Tokio

The next step is updating Mini Tokio to receive waker notifications. We want the
Expand Down

0 comments on commit 6b79142

Please sign in to comment.