From 412eac66898ceee17eb077d2feb80ee2eb972025 Mon Sep 17 00:00:00 2001 From: "Dustin J. Mitchell" Date: Fri, 7 Jun 2024 16:39:14 -0400 Subject: [PATCH] Clarify the suggested steps in the pin page (#2130) The speaker notes suggest an evolution of the code to support a periodic timer, but the last step was under-specified. (As mentioned by @fw-immunant and referenced in #1536) --- src/concurrency/async-pitfalls/pin.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/concurrency/async-pitfalls/pin.md b/src/concurrency/async-pitfalls/pin.md index fc764a8a..27b70a1c 100644 --- a/src/concurrency/async-pitfalls/pin.md +++ b/src/concurrency/async-pitfalls/pin.md @@ -82,7 +82,7 @@ async fn main() { - Instead, add a `timeout_fut` containing that future outside of the `loop`: ```rust,compile_fail - let mut timeout_fut = sleep(Duration::from_millis(100)); + let timeout_fut = sleep(Duration::from_millis(100)); loop { select! { .., @@ -106,7 +106,18 @@ async fn main() { - This compiles, but once the timeout expires it is `Poll::Ready` on every iteration (a fused future would help with this). Update to reset - `timeout_fut` every time it expires. + `timeout_fut` every time it expires: + ```rust,compile_fail + let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100))); + loop { + select! { + _ = &mut timeout_fut => { + println!(..); + timeout_fut = Box::pin(sleep(Duration::from_millis(100))); + }, + } + } + ``` - Box allocates on the heap. In some cases, `std::pin::pin!` (only recently stabilized, with older code often using `tokio::pin!`) is also an option, but