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
#include <future>
#include <iostream>

int main() {
  std::future <int> myFuture = std::async([]() {
          return 10 * 10;
      });
  
  std::cout << "Doing other work...\n";
  
  // Retrieve the result
  std::cout << "The result is: " << myFuture.get();
}

$ ./a.out
Doing other work...
The result is: 100
Promise:
- We create a promise
- Pass promise to async function - Value is written to promise(inside async function)
- Value read outside async using future
#include <future>
#include <iostream>

int main() {
    std::promise <int> myPromise;

    // Get the future linked to that promise
    std::future <int> myFuture = myPromise.get_future();
  
    std::async(std::launch::async, [](std::promise <int> prom) {
        int res = 10 * 10;
        prom.set_value(res); // set promise
    }, std::move(myPromise));
  
    std::cout << "Doing other work...\n";
  
    std::cout << "The result is: " << myFuture.get();
}
            

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