3 ms·
I don't think they are mutually exclusive. You can use async and threads at the same time.
by zekica 5y ago
I don't think they are mutually exclusive. You can use async and threads at the same time.
- lmm 5y agoYou can't really in rust, because it doesn't let you abstract over async-vs-not. If your function does something that a caller might want to happen async, it has to make a choice about whether to do it in an async way and return future (cumbersome and inefficient to use from blocking thread-based applications), or do it in a blocking way (unsuitable for use from async applications).
- Arnavion 5y agoFunction 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.