[2026] 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 작업
- 🔥 백그라운드 계산
📚 목차
- std::async - 간단한 비동기 실행
- promise와 future - 스레드 간 통신
- launch 정책 - 실행 방식 제어
- 예외 처리 - 안전한 비동기 코드
- 실전 예제 - 병렬 데이터 처리
- 자주 하는 실수와 해결법
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 관계
아래 코드는 mermaid를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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();
}
동작 흐름
다음은 mermaid를 활용한 상세한 구현 코드입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
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 집약적, 긴 작업 |
| deferred | get() 시 | 현재 스레드 | 낮음 | 짧은 작업, 조건부 실행 |
| async|deferred | 구현 선택 | 자동 | 중간 | 일반적 사용 |
| 아래 코드는 cpp를 사용한 구현 예제입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다. 코드를 직접 실행해보면서 동작을 확인해보세요. |
// async: 새 스레드
auto f1 = async(launch::async, compute, 10);
// deferred: 지연 실행 (get() 호출 시)
auto f2 = async(launch::deferred, compute, 10);
// 자동 선택
auto f3 = async(compute, 10);
실전 예시
예시 1: 병렬 계산
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 비동기 처리를 통해 효율적으로 작업을 수행합니다, 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
#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: 파일 다운로드
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 비동기 처리를 통해 효율적으로 작업을 수행합니다, 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
#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: 예외 전달
다음은 cpp를 활용한 상세한 구현 코드입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다, 에러 처리를 통해 안정성을 확보합니다, 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
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
다음은 cpp를 활용한 상세한 구현 코드입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다, 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
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() 여러 번 호출
아래 코드는 cpp를 사용한 구현 예제입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
// ❌ get()은 한 번만
future<int> f = async(compute, 10);
int x = f.get();
// int y = f.get(); // 예외 발생
// ✅ 결과 저장
int result = f.get();
문제 2: future 소멸
아래 코드는 cpp를 사용한 구현 예제입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
// ❌ future 소멸 시 대기
{
auto f = async(launch::async, compute, 10);
} // 여기서 대기 (블로킹)
// ✅ 명시적 대기
auto f = async(launch::async, compute, 10);
f.wait();
문제 3: 예외 무시
아래 코드는 cpp를 사용한 구현 예제입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다, 에러 처리를 통해 안정성을 확보합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// ❌ 예외 무시
auto f = async(launch::async, {
throw runtime_error("에러");
});
// f.get() 호출 안하면 예외 무시됨
// ✅ 예외 처리
try {
f.get();
} catch (const exception& e) {
cout << e.what() << endl;
}
promise 고급
다음은 cpp를 활용한 상세한 구현 코드입니다. 비동기 처리를 통해 효율적으로 작업을 수행합니다, 에러 처리를 통해 안정성을 확보합니다, 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
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.
💼 실전 예제: 병렬 이미지 처리
실무에서 자주 사용하는 패턴입니다:
#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로 비동기 함수 실행할 수 있나요? -
promise와future의 관계를 설명할 수 있나요? -
launch::async와launch::deferred의 차이를 아나요? - 예외를
future로 전달할 수 있나요? - 병렬 처리로 성능을 개선할 수 있나요? 다음 단계: C++ 코루틴으로 더 깔끔한 비동기 코드 작성하기
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ async & launch | “비동기 실행” 가이드
- C++ shared_future | 여러 스레드에서 future 결과 공유
- C++ std::thread 입문 | join 누락·디태치 남용 등 자주 하는 실수 3가지와 해결법
- C++ packaged_task | “패키지 태스크” 가이드