본문으로 건너뛰기
Previous
Next
C++ promise std::promise 완벽 가이드 | future와 비동기 프로그래밍

C++ promise std::promise 완벽 가이드 | future와 비동기 프로그래밍

C++ promise std::promise 완벽 가이드 | future와 비동기 프로그래밍

이 글의 핵심

C++ std::promise와 std::future로 배우는 비동기 프로그래밍. promise-future 패턴, std::async, launch 정책, 멀티스레드 통신까지 실전 예제로 마스터하기

🎯 이 글에서 배울 내용 (읽는 시간: 13분)

TL;DR: C++에서 비동기 작업의 결과를 받는 방법을 배웁니다. std::promise로 값을 설정하고, std::future로 결과를 받습니다. 콜백 지옥 없이 깔끔한 비동기 코드를 작성할 수 있습니다. 핵심 개념:

  • std::async: 간단한 비동기 실행
  • promise-future 패턴: 스레드 간 값 전달
  • launch 정책: 즉시 실행 vs 지연 실행
  • ✅ 예외 처리: 스레드 간 예외 전파 실무 활용:
  • 🔥 병렬 데이터 처리
  • 🔥 비동기 I/O 작업
  • 🔥 백그라운드 계산

📚 목차

  1. std::async - 간단한 비동기 실행
  2. promise와 future - 스레드 간 통신
  3. launch 정책 - 실행 방식 제어
  4. 예외 처리 - 안전한 비동기 코드
  5. 실전 예제 - 병렬 데이터 처리
  6. 자주 하는 실수와 해결법

std::async

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

compute 함수의 구현 예제입니다.

#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:


💼 실전 예제: 병렬 이미지 처리

실무에서 자주 사용하는 패턴입니다:

processImage 함수의 구현 예제입니다.

#include <future>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std;
// 이미지 처리 시뮬레이션
string processImage(const string& filename) {
    this_thread::sleep_for(chrono::seconds(1));
    return "Processed: " + filename;
}
int main() {
    vector<string> images = {
        "photo1.jpg", "photo2.jpg", "photo3.jpg", 
        "photo4.jpg", "photo5.jpg"
    };
    
    // 병렬 처리 시작
    vector<future<string>> futures;
    auto start = chrono::steady_clock::now();
    
    for (const auto& img : images) {
        futures.push_back(
            async(launch::async, processImage, img)
        );
    }
    
    // 결과 수집
    for (auto& f : futures) {
        cout << f.get() << endl;
    }
    
    auto end = chrono::steady_clock::now();
    auto duration = chrono::duration_cast<chrono::seconds>(end - start);
    
    cout << "\n총 처리 시간: " << duration.count() << "초" << endl;
    // 순차 처리: 5초, 병렬 처리: 1초!
}

성능 비교:

  • 순차 처리: 5초 (1초 × 5개)
  • 병렬 처리: 1초 (동시 실행)
  • 5배 빠름! 🚀

⚠️ 자주 하는 실수와 해결법

실수 1: future를 저장하지 않음

// ❌ 나쁜 예: future를 무시
async(launch::async, []{ 
    cout << "작업 실행" << endl; 
});
// 즉시 블로킹됨!
// ✅ 좋은 예: future 저장
auto f = async(launch::async, []{ 
    cout << "작업 실행" << endl; 
});
// 나중에 f.get()으로 결과 받기

실수 2: get()을 여러 번 호출

future<int> f = async(launch::async, []{ return 42; });
int x = f.get();  // ✅ OK
int y = f.get();  // ❌ 런타임 에러!

해결법: shared_future 사용

shared_future<int> sf = async(launch::async, []{ return 42; }).share();
int x = sf.get();  // ✅ OK
int y = sf.get();  // ✅ OK

실수 3: 예외를 무시

// ❌ 나쁜 예
auto f = async(launch::async, []{ 
    throw runtime_error("Error!"); 
});
// get()을 호출하지 않으면 예외가 무시됨
// ✅ 좋은 예
try {
    f.get();
} catch (const exception& e) {
    cerr << "에러: " << e.what() << endl;
}

🎓 학습 체크리스트

이 글을 다 읽었다면:

  • std::async로 비동기 함수 실행할 수 있나요?
  • promisefuture의 관계를 설명할 수 있나요?
  • launch::asynclaunch::deferred의 차이를 아나요?
  • 예외를 future로 전달할 수 있나요?
  • 병렬 처리로 성능을 개선할 수 있나요? 다음 단계: C++ 코루틴으로 더 깔끔한 비동기 코드 작성하기

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

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

관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ promise std::promise 완벽 가이드 | future와 비동기 프로그래밍」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ promise std::promise 완벽 가이드 | future와 비동기 프로그래밍」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, future, promise, async, 비동기, std::promise, std::future, 멀티스레드 등으로 검색하시면 이 글이 도움이 됩니다.