5 ms·
You can use `block_on` from the futures-lite crate (or from other crates) to synchronously call async functions. Not using async or async crates is not recomme
by devit 3y ago
You can use `block_on` from the futures-lite crate (or from other crates) to synchronously call async functions.
Not using async or async crates is not recommended since most new or updated high quality crates now use async.
- devit 3y agoAnd note that it's a good thing that crates are async, because async-in-sync using block_on has only some potential small CPU time overhead, while sync-in-async requires having a thread for each concurrent usage and has potentially catastrophic memory overhead since a user and kernel mode stacks and thread data structures could in some cases be 100-1000x bigger than the future; hence, an async-only create is much better than a sync-only crate (although of course a crate that supports both is ideal from the user's point of view).
- Grimburger 3y agoThat still requires pulling in the few hundred dependencies from tokio though?
- steveklabnik 3y agoThat doesn't seem to be the case: ~> cd tmp\ ~/tmp> cargo new futures-test Created binary (application) `futures-test` package ~/tmp> cd futures-test ~/tmp/futures-test> cargo add futures-lite Updating crates.io index Adding futures-lite v1.13.0 to dependencies. Features: + alloc + fastrand + futures-io + memchr + parking + std + waker-fn ~/tmp/futures-test> code . ~/tmp/futures-test> open src\main.rs use futures_lite::future; fn main() { future::block_on(async { println!("Hello world!"); }) } ~/tmp/futures-test> cargo run Compiling futures-io v0.3.28 Compiling memchr v2.6.3 Compiling pin-project-lite v0.2.13 Compiling fastrand v1.9.0 Compiling waker-fn v1.1.1 Compiling parking v2.1.1 Compiling futures-core v0.3.28 Compiling futures-lite v1.13.0 Compiling futures-test v0.1.0 (C:\Users\steve\tmp\futures-test) Finished dev [unoptimized + debuginfo] target(s) in 1.74s Running `target\debug\futures-test.exe` Hello world! 11 total dependencies.
- Matthias247 3y agoSure. But those async functions can't do any IO. If you need to use IO functions (e.g. from tokio), then you would still need to import that framework.
- steveklabnik 3y agoIt is true that if you need to use Tokio, you'll end up using Tokio. That is not what was being suggested, though: it was just that tokio is not required for a simple block_on implementation. If you're already using tokio, using its block_on of course makes sense. But in that case, you're not adding "few hundred dependencies," you're using the ones that you're already using. And like, to be clear, "the few hundred dependencies from tokio" is also misleading. A `cargo add tokio --features full` adds 43 dependencies to your Cargo.lock at the time of writing.
- Grimburger 3y agoThankyou for being correct and wonderful, as always. I was more aiming for the hyperbole crowd though man.