How can I pause an async task in Rust?
Swift has withCheckedContinuation(function:_:)
that pauses current task and returns saved context that can be resumed at desired time. (a.k.a. call/cc)
tokio has tokio::task::yield_now, but it can resume automatically, so that's not what I'm looking for. I mean "pause" that will never resume without explicit command.
Now I'm looking into tokio manual. It defines several synchronization features in tokio::sync module, but I couldn't find a function to pause a task directly. Am I supposed to use only the synchronization feature to simulate the suspend? Or am I missing something here?
I don't know anything built-in, but you can build your own.
You need access to the
Wakerto unpark a future. You also need to keep track of whether the futute has been manually unparked, because futures can be waked by the runtime even if nobody ordered them to.There are various ways to write this code, here is one:
Then you call it like
park(|p| { ... }).await.Example.