C++ future와 promise | "비동기" 가이드

C++ future와 promise | "비동기" 가이드

이 글의 핵심

C++ future와 promise에 대한 실전 가이드입니다.

std::async

async 비동기 실행에서 다루는 std::async로 비동기 실행 후 future로 결과를 받을 수 있습니다.

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

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

int main() {
    // 비동기 실행
    future<int> result = async(launch::async, compute, 10);
    
    cout << "계산 중..." << endl;
    
    // 결과 대기
    cout << "결과: " << result.get() << endl;  // 100
}

promise와 future

promise-future 관계

graph LR
    A[promise] -->|get_future| B[future]
    C[생산자 스레드] -->|set_value| A
    B -->|get| D[소비자 스레드]
    
    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);  // 결과 설정
}

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

동작 흐름

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 정책

정책별 특성 비교

정책실행 시점스레드오버헤드적합한 작업
async즉시새 스레드높음CPU 집약적, 긴 작업
deferredget()현재 스레드낮음짧은 작업, 조건부 실행
async|deferred구현 선택자동중간일반적 사용
// async: 새 스레드
auto f1 = async(launch::async, compute, 10);

// deferred: 지연 실행 (get() 호출 시)
auto f2 = async(launch::deferred, compute, 10);

// 자동 선택
auto f3 = async(compute, 10);

실전 예시

예시 1: 병렬 계산

#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;
    
    // 병렬 실행
    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));
    }
    
    // 결과 수집
    int total = 0;
    for (auto& f : futures) {
        total += f.get();
    }
    
    cout << "합계: " << total << endl;
}

예시 2: 파일 다운로드

#include <future>
#include <vector>

string downloadFile(const string& url) {
    // 다운로드 시뮬레이션
    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;
    
    // 병렬 다운로드
    for (const auto& url : urls) {
        futures.push_back(async(launch::async, downloadFile, url));
    }
    
    // 결과 수집
    for (auto& f : futures) {
        cout << f.get() << endl;
    }
}

예시 3: 타임아웃

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

int main() {
    auto f = async(launch::async, longComputation);
    
    // 2초 대기
    if (f.wait_for(chrono::seconds(2)) == future_status::ready) {
        cout << "결과: " << f.get() << endl;
    } else {
        cout << "타임아웃" << endl;
    }
}

예시 4: 예외 전달

int divide(int a, int b) {
    if (b == 0) {
        throw runtime_error("0으로 나눌 수 없음");
    }
    return a / b;
}

int main() {
    auto f = async(launch::async, divide, 10, 0);
    
    try {
        int result = f.get();  // 예외 재발생
        cout << result << endl;
    } catch (const exception& e) {
        cout << "에러: " << 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();
    
    // 여러 스레드에서 접근 가능
    thread t1([sf]() {
        cout << "스레드 1: " << sf.get() << endl;
    });
    
    thread t2([sf]() {
        cout << "스레드 2: " << sf.get() << endl;
    });
    
    t1.join();
    t2.join();
}

자주 발생하는 문제

문제 1: get() 여러 번 호출

// ❌ get()은 한 번만
future<int> f = async(compute, 10);
int x = f.get();
// int y = f.get();  // 예외 발생

// ✅ 결과 저장
int result = f.get();

문제 2: future 소멸

// ❌ future 소멸 시 대기
{
    auto f = async(launch::async, compute, 10);
}  // 여기서 대기 (블로킹)

// ✅ 명시적 대기
auto f = async(launch::async, compute, 10);
f.wait();

문제 3: 예외 무시

// ❌ 예외 무시
auto f = async(launch::async,  {
    throw runtime_error("에러");
});
// f.get() 호출 안하면 예외 무시됨

// ✅ 예외 처리
try {
    f.get();
} catch (const exception& e) {
    cout << e.what() << endl;
}

promise 고급

void compute(promise<int> p, int x) {
    try {
        if (x < 0) {
            throw invalid_argument("음수 불가");
        }
        
        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 << "에러: " << e.what() << endl;
    }
    
    t.join();
}

FAQ

Q1: async vs thread?

A:

  • async: 간단, 결과 반환
  • thread: 세밀한 제어

Q2: future는 언제 사용하나요?

A:

  • 비동기 작업
  • 병렬 계산
  • 결과 전달

Q3: 성능은?

A: 스레드 생성 비용. 작은 작업은 오버헤드 클 수 있음.

Q4: future는 재사용 가능?

A: 아니요. get()은 한 번만 호출 가능.

Q5: 타임아웃은?

A: wait_for()나 wait_until() 사용.

Q6: future/promise 학습 리소스는?

A:

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

관련 글: async 비동기 실행, shared_future, 스레드 기초, packaged_task.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ async & launch | “비동기 실행” 가이드
  • C++ shared_future | 여러 스레드에서 future 결과 공유
  • C++ std::thread 입문 | join 누락·디태치 남용 등 자주 하는 실수 3가지와 해결법
  • C++ packaged_task | “패키지 태스크” 가이드

관련 글

  • C++ async & launch |
  • C++ 코루틴 |
  • C++ packaged_task |
  • C++ shared_future | 여러 스레드에서 future 결과 공유
  • JavaScript 비동기 프로그래밍 | Promise, async/await 완벽 정리