Futures and Promises

Asynchronous results

Interview Relevant: Async programming

Futures and Promises

Get results from asynchronous operations.

Code Examples

Futures and promises for async results.

cpp
1#include <future>
2
3// Promise sets value, future gets it
4void compute(promise<int> prom) {
5    int result = 42;  // Some computation
6    prom.set_value(result);
7}
8
9promise<int> prom;
10future<int> fut = prom.get_future();
11thread t(compute, move(prom));
12int result = fut.get();  // Blocks until ready
13t.join();
14
15// Check if ready
16if (fut.wait_for(chrono::seconds(0)) == future_status::ready) {
17    int val = fut.get();
18}
19
20// Packaged task
21packaged_task<int(int, int)> task([](int a, int b) {
22    return a + b;
23});
24future<int> f = task.get_future();
25thread t2(move(task), 3, 4);
26cout << f.get();  // 7
27t2.join();
28
29// Exception through promise
30void mightFail(promise<int> prom) {
31    try {
32        throw runtime_error("Error!");
33    } catch (...) {
34        prom.set_exception(current_exception());
35    }
36}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In