Skip to content

🚀 C++ Tutorial: Using std::async for Asynchronous Programming

What is std::async?

std::async is a function in the C++ Standard Library (since C++11) that allows you to run a function asynchronously (in a separate thread or lazily, depending on the launch policy). It’s a simple way to perform tasks in parallel, making your programs more responsive and efficient.


Why Use std::async?

  • Parallelism: Run tasks in parallel to utilize multiple CPU cores.
  • Responsiveness: Keep your main thread free for user interaction or other tasks.
  • Simplicity: No need to manage threads directly.

Basic Usage

#include <iostream>
#include <future>
#include <chrono>

int slow_add(int a, int b) {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return a + b;
}

int main() {
    // Launch slow_add asynchronously
    std::future<int> result = std::async(std::launch::async, slow_add, 3, 4);

    std::cout << "Doing other work while waiting for result...\n";

    // Get the result (waits if not ready)
    int sum = result.get();

    std::cout << "Result: " << sum << std::endl;
    return 0;
}

Key Concepts

1. Launch Policies

  • std::launch::async: Always runs the function in a new thread.
  • std::launch::deferred: Runs the function only when you call .get() or .wait(), in the same thread.
  • Default: May choose either policy.

Example:

std::async(std::launch::async, my_function);    // New thread
std::async(std::launch::deferred, my_function); // Deferred until needed

2. Return Value: std::future

  • std::async returns a std::future<T>, where T is the return type of your function.
  • Call .get() on the future to retrieve the result (waits if not ready).

Error Handling

Exceptions thrown in the async function are stored and rethrown when you call .get() on the future.

auto f = std::async([]() -> int {
    throw std::runtime_error("Oops!");
    return 42;
});
try {
    int value = f.get(); // Throws here
} catch (const std::exception& e) {
    std::cout << "Caught exception: " << e.what() << std::endl;
}

When to Use std::async

  • Running time-consuming computations in the background.
  • Parallelizing independent tasks.
  • Avoiding manual thread management.

Tips

  • Don’t forget to call .get() on your future, or exceptions may go unnoticed.
  • Use std::future::wait() if you just want to wait for completion without retrieving the result.

Summary

  • std::async is a powerful tool for simple asynchronous programming in C++.
  • It helps you run functions in parallel and retrieve results easily.
  • Use it to write cleaner, more responsive, and efficient C++ code!