Async Programming in C++
Meaning of async?
std::async run a function asynchronously.
std::future<T> is the result of async function, that
will be available later
std::promise communication channel endpoint between main
and async function.
A promise and its future are two ends of one one-time
communication channel
We can think future and promise as: write, read end of pipe
--------Pipe---------
future > |write async read| > Read
|end function end|
--------------------
Simple example
| aync, future | aync, promise, future |
|---|---|
|
Promise: - We create a promise - Pass promise to async function - Value is written to promise(inside async function) - Value read outside async using future
|
Async Rust
async, await
async fn calculate() -> i32 {
20 + 22
}
#[tokio::main]
async fn main() {
let result = calculate().await;
println!("Answer: {result}");
}
C++'s std::promise
Has no twin in Rust.
We can think one-shot channel: the sender produces
one value and the receiver awaits it as similar concept