C++ future and promise | "Asynchronous" guide

C++ future and promise | "Asynchronous" guide

이 글의 핵심

A practical guide to C++ futures and promises.

std::async

After executing asynchronously with std::async, which is covered in async asynchronous execution, you can receive the result as future.

#include <future>
#include <iostream>
using namespace std;

int compute(int x) {
    this_thread::sleep_for(chrono::seconds(1));
    return x * x;
}

int main() {
    // asynchronous execution
    future<int> result = async(launch::async, compute, 10);
    
cout << "Calculating..." << endl;
    
    // waiting for results
cout << "Result: " << result.get() << endl;  // 100
}

promise and future

promise-future relationship

graph LR
    A[promise] -->|get_future| B[future]
C[producer thread] -->|set_value| A
B -->|get| D[consumer thread]
    
    style A fill:#e1f5ff
    style B fill:#ffe1e1
    style C fill:#e1ffe1
    style D fill:#ffe1ff
void compute(promise<int> p, int x) {
    this_thread::sleep_for(chrono::seconds(1));
    p.set_value(x * x);  // Result settings
}

int main() {
    promise<int> p;
    future<int> f = p.get_future();
    
    thread t(compute, move(p), 10);
    
cout << "Calculating..." << endl;
cout << "Result: " << f.get() << endl;  // 100
    
    t.join();
}

Action flow

sequenceDiagram
    participant Main as Main Thread
    participant Promise as promise
    participant Future as future
    participant Worker as Worker Thread

    Main->>Promise: create
    Main->>Future: get_future()
    Main->>Worker: start thread

    Main->>Main: other work
    Worker->>Worker: compute

    Main->>Future: get()
    Note over Main,Future: waiting...
    
    Worker->>Promise: set_value(result)
    Promise->>Future: deliver result
    Future->>Main: return result

    Main->>Worker: join()

launch policy

Comparison of characteristics by policy

policyWhen to runthreadoverheadsuitable job
asyncImmediatelynew threadHighCPU intensive, long task
deferredWhen get()current threadlowShort tasks, conditional execution
async|deferredImplementation SelectionautomaticmiddleGeneral Use
// async: new thread
auto f1 = async(launch::async, compute, 10);

// deferred: Deferred execution (when calling get())
auto f2 = async(launch::deferred, compute, 10);

// automatic selection
auto f3 = async(compute, 10);

Practical example

Example 1: Parallel computation

#include <future>
#include <vector>
#include <numeric>

int sumRange(int start, int end) {
    int sum = 0;
    for (int i = start; i < end; i++) {
        sum += i;
    }
    return sum;
}

int main() {
    const int N = 1000000;
    const int numThreads = 4;
    const int chunkSize = N / numThreads;
    
    vector<future<int>> futures;
    
    // parallel execution
    for (int i = 0; i < numThreads; i++) {
        int start = i * chunkSize;
        int end = (i + 1) * chunkSize;
        
        futures.push_back(async(launch::async, sumRange, start, end));
    }
    
    // Results collection
    int total = 0;
    for (auto& f : futures) {
        total += f.get();
    }
    
cout << "Total: " << total << endl;
}

Example 2: Downloading a file

#include <future>
#include <vector>

string downloadFile(const string& url) {
    // download simulation
    this_thread::sleep_for(chrono::seconds(1));
    return "Content from " + url;
}

int main() {
    vector<string> urls = {
        "http://example.com/file1",
        "http://example.com/file2",
        "http://example.com/file3"
    };
    
    vector<future<string>> futures;
    
    // parallel download
    for (const auto& url : urls) {
        futures.push_back(async(launch::async, downloadFile, url));
    }
    
    // Results collection
    for (auto& f : futures) {
        cout << f.get() << endl;
    }
}

Example 3: Timeout

int longComputation() {
    this_thread::sleep_for(chrono::seconds(5));
    return 42;
}

int main() {
    auto f = async(launch::async, longComputation);
    
    // wait 2 seconds
    if (f.wait_for(chrono::seconds(2)) == future_status::ready) {
cout << "Result: " << f.get() << endl;
    } else {
cout << "timeout" << endl;
    }
}

Example 4: Passing an exception

int divide(int a, int b) {
    if (b == 0) {
throw runtime_error("Cannot divide by 0");
    }
    return a / b;
}

int main() {
    auto f = async(launch::async, divide, 10, 0);
    
    try {
        int result = f.get();  // Exception reoccurrence
        cout << result << endl;
    } catch (const exception& e) {
cout << "Error: " << e.what() << endl;
    }
}

shared_future

int compute() {
    this_thread::sleep_for(chrono::seconds(1));
    return 42;
}

int main() {
    shared_future<int> sf = async(launch::async, compute).share();
    
    // Accessible from multiple threads
    thread t1([sf]() {
cout << "Thread 1: " << sf.get() << endl;
    });
    
    thread t2([sf]() {
cout << "Thread 2: " << sf.get() << endl;
    });
    
    t1.join();
    t2.join();
}

Frequently occurring problems

Problem 1: get() called multiple times

// ❌ get() only once
future<int> f = async(compute, 10);
int x = f.get();
// int y = f.get();  // exception occurs

// ✅ Save results
int result = f.get();

Problem 2: future destruction

// ❌ Wait when future expires
{
    auto f = async(launch::async, compute, 10);
}  // Wait here (blocking)

// ✅ Explicit wait
auto f = async(launch::async, compute, 10);
f.wait();

Problem 3: Ignoring exceptions

// ❌ Ignoring exceptions
auto f = async(launch::async,  {
throw runtime_error("error");
});
// If f.get() is not called, the exception is ignored.

// ✅ Exception handling
try {
    f.get();
} catch (const exception& e) {
    cout << e.what() << endl;
}

promise advanced

void compute(promise<int> p, int x) {
    try {
        if (x < 0) {
throw invalid_argument("Negative numbers are not allowed");
        }
        
        p.set_value(x * x);
    } catch (...) {
        p.set_exception(current_exception());
    }
}

int main() {
    promise<int> p;
    future<int> f = p.get_future();
    
    thread t(compute, move(p), -10);
    
    try {
        cout << f.get() << endl;
    } catch (const exception& e) {
cout << "Error: " << e.what() << endl;
    }
    
    t.join();
}

FAQ

Q1: async vs thread?

A:

  • async: simple, returns results
  • thread: Fine-grained control

Q2: When do you use future?

A:

  • Asynchronous operations
  • Parallel calculation
  • Deliver results

Q3: What is the performance?

A: Thread creation cost. Small tasks can have large overhead.

Q4: Is future reusable?

A: No. get() can only be called once.

Q5: What about timeout?

A: Use wait_for() or wait_until().

Q6: What are future/promise learning resources?

A:

  • “C++ Concurrency in Action”
  • cppreference.com
  • “Effective Modern C++”

Related articles: async asynchronous execution, shared_future, thread basics, packaged_task.


Good article to read together (internal link)

Here’s another article related to this topic.

  • C++ async & launch | “Asynchronous Execution” Guide
  • C++ shared_future | Share future results across multiple threads
  • C++ std::thread introduction | 3 common mistakes such as missing joins and overuse of detach and solutions
  • C++ packaged_task | “Packaged Task” Guide

Practical tips

These are tips that can be applied right away in practice.

Debugging tips

  • If you run into a problem, check the compiler warnings first.
  • Reproduce the problem with a simple test case

Performance Tips

  • Don’t optimize without profiling
  • Set measurable indicators first

Code review tips

  • Check in advance for areas that are frequently pointed out in code reviews.
  • Follow your team’s coding conventions

Practical checklist

This is what you need to check when applying this concept in practice.

Before writing code

  • Is this technique the best way to solve the current problem?
  • Can team members understand and maintain this code?
  • Does it meet the performance requirements?

Writing code

  • Have you resolved all compiler warnings?
  • Have you considered edge cases?
  • Is error handling appropriate?

When reviewing code

  • Is the intent of the code clear?
  • Are there enough test cases?
  • Is it documented?

Use this checklist to reduce mistakes and improve code quality.


Keywords covered in this article (related search terms)

This article will be helpful if you search for C++, future, promise, async, asynchronous, etc.


  • C++ async & launch |
  • C++ Coroutine |
  • C++ packaged_task |
  • C++ shared_future | Share future results across multiple threads
  • JavaScript Asynchronous Programming | Promise, async/await complete summary