3 ms·
Function is async and you want to run it synchronously? Create an async runtime and use its equivalent of `runtime.block_on(async_fn())` to drive the future to
by Arnavion 5y ago
Function is async and you want to run it synchronously? Create an async runtime and use its equivalent of `runtime.block_on(async_fn())` to drive the future to completion synchronously.
Function is blocking and you want to use it in an async context without blocking the async worker thread? Use your runtime's equivalent of `spawn_blocking(|| sync_fn()).await` that will run the function call in a threadpool dedicated for blocking tasks.
(Both those examples are for tokio.)
- lmm 5y agoRight, and in both cases you end up being inefficient and using more threads than you wanted to (and in the second case, potentially undermine the whole point of using async at all).
- Arnavion 5y ago>in both cases you end up being inefficient and using more threads than you wanted to There are no extra threads in the former case. >(and in the second case, potentially undermine the whole point of using async at all) If code is blocking for long periods of time, it shouldn't be running on the async worker thread in the first place. Marking such a function `async` would be wrong. If I write a tight loop that takes seconds to do its job, putting an `async` on the function is worse than not having it. Spawning such work in a different thread is correct. There's no "whole point of using async" that is being "undermined".
- lmm 5y ago> If code is blocking for long periods of time, it shouldn't be running on the async worker thread in the first place. Marking such a function `async` would be wrong. Right, you need to go right down and e.g. use a non-blocking I/O primitive instead of a blocking I/O primitive. Rust gives you no way to polymorphically do one or the other.