shared_future — std::shared_future

shared_future — std::shared_future

std::shared_future 클래스 템플릿은 비동기 연산의 결과에 접근하는 메커니즘을 제공해요. C++11에서 도입됐어요. <future> 헤더에 있어요.

std::future와 달리, shared_future복사 가능하고, 여러 스레드가 같은 결과를 함께 기다릴 수 있어요.

출처: cppreference

본문

// <future> 헤더, C++11
template< class T > class shared_future;       // (1)
template< class T > class shared_future<T&>;   // (2)
template<> class shared_future<void>;          // (3)

사용 예

#include <future>
#include <thread>
#include <vector>

std::promise<int> p;
std::shared_future<int> sf = p.get_future();   // future → shared_future

// 여러 스레드가 같은 결과를 각각 기다림
std::vector<std::thread> ts;
for (int i = 0; i < 4; ++i) {
    ts.emplace_back([sf] {          // shared_future 복사 캡처
        int v = sf.get();           // 각각 get 가능
    });
}
p.set_value(42);                    // 결과 설정
for (auto& t : ts) t.join();

future → shared_future

std::future::share()로 변환할 수 있어요.

std::future<int> f = std::async([] { return 7; });
std::shared_future<int> sf = f.share();   // f는 더 이상 사용 불가

주요 연산

연산 설명
get() 결과 반환 (여러 번 가능)
wait() 블로킹 대기
wait_for(dur) / wait_until(tp) 시간 제한 대기
valid() 유효성

특징

  • 복사 가능 — 여러 스레드로 전달해 각각 get() 호출 가능.
  • std::future는 1회용(get() 한 번)이지만, shared_future는 반복·다중 접근이 가능해요.
  • T&/void 특수화 지원.

std::shared_future는 하나의 비동기 결과를 여러 소비자가 공유해야 할 때 사용해요.

더 알아보기 (Learn more)

cppreference