C++C++ Explainer
C++ · 6 · Concurrency27 / 36 · 75%

std::async, future & promise

Get a value back from another thread, exceptions included.

Examples: async, future::get, promise, packaged_task

shortcuts: ← prev · → next · M mark
1

std::async

Launch work and receive a future for the result.

Example
example
#include <future>

auto fut = std::async(std::launch::async, [] {
    return heavy_computation();
});

do_other_work();
int result = fut.get();   // blocks until ready
WATCH OUT
Without std::launch::async the implementation may defer the task and run it lazily on get().
2

Exceptions Travel

A throw inside the task is rethrown by get().

Example
example
auto f = std::async(std::launch::async, []{ throw std::runtime_error("boom"); });
try { f.get(); }
catch (const std::exception& e) { std::cerr << e.what(); }
3

promise / future

Manual handoff when the value is produced somewhere else.

Example
example
std::promise<int> p;
std::future<int> f = p.get_future();

std::thread t([&p]{ p.set_value(42); });
std::cout << f.get();   // 42
t.join();
4

The async Destructor Trap

The future returned by async blocks in its destructor.

Example
example
{
    std::async(std::launch::async, slow_task);  // temporary future
}   // blocks HERE until slow_task finishes — looks synchronous
Store the future in a named variable if you want real concurrency.