async — std::async
async — std::async
std::async는 함수를 비동기적으로(또는 지연해서) 실행하고, 그 결과를 담는 std::future를 반환하는 함수 템플릿이에요. C++11에서 도입됐어요. <future> 헤더에 있어요.
비동기 작업의 결과를 나중에 future::get()으로 받을 수 있어요.
출처: cppreference
본문
// <future> 헤더, C++11
template< class F, class... Args >
std::future</* see below */> async( F&& f, Args&&... args ); // (1)
template< class F, class... Args >
std::future</* see below */> async( std::launch policy,
F&& f, Args&&... args ); // (2)
- (1) 정책을 지정하지 않음 — 구현이
async또는deferred를 선택 (구현 정의) - (2) 정책을 명시 (
std::launch::async또는std::launch::deferred)
#include <future>
#include <iostream>
int compute(int x) { return x * x; }
// (1) 정책 미지정
std::future<int> f = std::async(compute, 5);
std::cout << f.get() << '\n'; // 25
// (2) 명시적으로 async
std::future<int> g = std::async(std::launch::async, compute, 7);
std::cout << g.get() << '\n'; // 49
launch 정책
std::launch::async // 새 스레드에서 실행
std::launch::deferred // get() 호출 시까지 지연된 실행
std::launch::async | std::launch::deferred // 구현이 선택
람다 사용
auto f = std::async(std::launch::async, [](int a, int b) {
return a + b;
}, 3, 4);
std::cout << f.get() << '\n'; // 7
특징
future::get()은 결과를 기다렸다가 받아요. 결과를 받기 전에 파괴되면 데드락이 될 수 있어 주의.- 예외가 발생하면
get()에서 그 예외가 다시 던져져요. deferred인 경우get()이 호출될 때 실행돼요.
try {
auto f = std::async(std::launch::async, [] { throw std::runtime_error("!"); });
f.get(); // std::runtime_error 재전달
} catch (const std::runtime_error&) {
// 처리
}
std::async는 간단한 비동기 실행과 결과 수집에 가장 편리한 도구예요. 결과가 필요 없는 Fire-and-forget도 가능하지만, 수명 관리를 위해 결과를 받아두는 것이 좋아요.