thread_shared_future

thread_shared_future (공유 미래)

std::shared_future는 비동기 연산의 결과에 접근할 수 있게 해주는 클래스 템플릿이에요. std::future와 달리 복사가 가능해서 여러 스레드가 같은 공유 상태를 동시에 기다릴 수 있답니다. 이 페이지에서는 shared_future의 정의, 멤버 함수, 그리고 실제 사용 예제를 자세히 설명할게요.

출처: cppreference

본문

정의

<future> 헤더에 정의됨
template < class T > class shared_future ; (1) (C++11부터)
template < class T > class shared_future < T &> ; (2) (C++11부터)
template <> class shared_future < void > ; (3) (C++11부터)

클래스 템플릿 std::shared_future는 비동기 연산의 결과에 접근하는 메커니즘을 제공해요. std::future와 비슷하지만, 여러 스레드가 같은 공유 상태를 기다릴 수 있다는 점이 달라요. std::future는 이동만 가능해서(그래서 특정 비동기 결과를 참조하는 인스턴스가 하나뿐이지만), std::shared_future는 복사 가능하고 여러 공유 미래 객체가 같은 공유 상태를 참조할 수 있어요.

여러 스레드가 같은 공유 상태에 접근할 때, 각 스레드가 자신의 shared_future 객체 복사본을 통해 접근한다면 안전해요.

멤버 함수

(생성자) 미래 객체를 생성해요 (공용 멤버 함수)
(소멸자) 미래 객체를 소멸해요 (공용 멤버 함수)
operator= 내용을 할당해요 (공용 멤버 함수)
결과 가져오기
get 결과를 반환해요 (공용 멤버 함수)
상태
valid 미래 객체가 공유 상태를 가지고 있는지 확인해요 (공용 멤버 함수)
wait 결과를 사용할 수 있을 때까지 기다려요 (공용 멤버 함수)
wait_for 결과를 기다리되, 지정된 제한 시간 동안 사용할 수 없으면 반환해요 (공용 멤버 함수)
wait_until 결과를 기다리되, 지정된 시점이 될 때까지 사용할 수 없으면 반환해요 (공용 멤버 함수)

예제

shared_future는 여러 스레드에 동시에 신호를 보내는 데 사용할 수 있어요. std::condition_variable::notify_all()과 비슷한 역할을 한답니다.

#include <chrono>
#include <future>
#include <iostream>

int main()
{   
    std::promise<void> ready_promise, t1_ready_promise, t2_ready_promise;
    std::shared_future<void> ready_future(ready_promise.get_future());

    std::chrono::time_point<std::chrono::high_resolution_clock> start;

    auto fun1 = [&, ready_future]() -> std::chrono::duration<double, std::milli> 
    {
        t1_ready_promise.set_value();
        ready_future.wait(); // waits for the signal from main()
        return std::chrono::high_resolution_clock::now() - start;
    };


    auto fun2 = [&, ready_future]() -> std::chrono::duration<double, std::milli> 
    {
        t2_ready_promise.set_value();
        ready_future.wait(); // waits for the signal from main()
        return std::chrono::high_resolution_clock::now() - start;
    };

    auto fut1 = t1_ready_promise.get_future();
    auto fut2 = t2_ready_promise.get_future();

    auto result1 = std::async(std::launch::async, fun1);
    auto result2 = std::async(std::launch::async, fun2);

    // wait for the threads to become ready
    fut1.wait();
    fut2.wait();

    // the threads are ready, start the clock
    start = std::chrono::high_resolution_clock::now();

    // signal the threads to go
    ready_promise.set_value();

    std::cout << "Thread 1 received the signal "
              << result1.get().count() << " ms after start\n"
              << "Thread 2 received the signal "
              << result2.get().count() << " ms after start\n";
}

가능한 출력:

Thread 1 received the signal 0.072 ms after start
Thread 2 received the signal 0.041 ms after start

같이 보기

async (C++11) 함수를 비동기적으로(잠재적으로 새 스레드에서) 실행하고 결과를 담을 std::future를 반환해요 (함수 템플릿)
future (C++11) 비동기적으로 설정되는 값을 기다려요 (클래스 템플릿)

더 알아보기 (Learn more)

cppreference