async fn foo() {
while true {
do_expehsive_computation();
yield();
}
}
Is there an idiomatic way in async rust to say "yield"; i.e. "let other scheduled async tasks run; then come back to me" ?
async fn foo() {
while true {
do_expehsive_computation();
yield();
}
}
Is there an idiomatic way in async rust to say "yield"; i.e. "let other scheduled async tasks run; then come back to me" ?
If you use Tokio, there's literally task::yield_now
. For other executors, you may want to take inspiration from there (or look for something similar).
My fault for not stating this upfront. I am using wasm_bindgen_futures: wasm_bindgen_futures - Rust
which seems to shows nothing.
You can definitely use futures_lite::yield_now() as mentioned by @nerditation
The idea is just to await
a Future
that returns Poll::Pending
once in order to yield back to the task scheduler. (This future, when polled, must also wake
its own task immediately when returning Poll::Pending
, in order to let the runtime know that the future may be polled again immediately.) There is nothing really "runtime-dependant" here.
Note that if do_expensive_computation()
takes lot of time you might want to insert some yield
in there too. Also note that yield_now()
and similar return a Future
, so you need to .await
them (as opposed to your example in the OP)