What is Asynchronous?
Model runs larger number of tasks on a limited number of threads, because the per-task overhead is typically very low.
Eg: I/O-bound tasks(Network or file I/O)
Async vs Threading
Async | Threading | |
---|---|---|
Concurrency | Done inside single thread. Uses event loops or similar mechanisms to efficiently handle tasks | Executing multiple threads of execution concurrently. |
Resource Overhead | lower resource overhead compared to multithreading. Since reduces context-switching and memory overhead | High resource overhead. Since each thread has its own stack and context |
Complexity | Simpler for certains cases like I/O-bound operations bcoz avoids deadlocks, race conditions | More complex since it involves race conditions, deadlocks, and other concurrency issues |
Performance | Better performance for I/O-bound applications. Not suited for CPU-bound tasks. | Better performance for CPU-bound tasks |
Rust
async, await, block_on()
-
async: keyword is syntactic sugar. The compiler replaces the return type with a future
await
async main(): You cannot make main async, without additional instructions to the compiler You need an executor to run async code
block_on(): blocks the current thread until the provided future has run to completion
use futures::executor::block_on;
async fn count_to(count: i32) {
for i in 0..count {
println!("Count is: {i}!");
}
}
async fn async_main(count: i32) {
count_to(count).await;
}
fn main() {
block_on(async_main(4));
}
$ cargo run
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Future
-
Asynchronous operation is based on "futures", which represent work that may be completed in the future.
Futures are "polled" until they signal that they are complete
future is trait.
await
-
The .await keyword, applied to a Future, causes the current async function to pause until that Future is ready,
and then evaluates to its output.
await is used to wait for another async function.
await vs block_on()
await | block_on() | |
---|---|---|
Blocks current thread | no | yes |
wait for future to complete | yes | yes |
Other tasks in async function can run? | yes | no |
C++
-
Future object is returned by the async function.
Promise is returned by async.
|
|