thread_future

thread_future (비동기 연산 결과 접근)

std::future는 비동기 연산의 결과에 접근할 수 있는 메커니즘을 제공하는 클래스 템플릿이에요. std::async, std::packaged_task 또는 std::promise를 통해 수행된 비동기 연산은 그 연산을 생성한 쪽에 std::future 객체를 전달할 수 있어요. 생성자는 다양한 메서드를 사용해 결과를 조회하거나 기다리거나 추출할 수 있답니다.

출처: cppreference

본문

<future> 헤더에 정의되어 있어요.

정의
template < class T > class future; (1) (since C++11)
template < class T > class future < T &>; (2) (since C++11)
template <> class future < void >; (3) (since C++11)

std::future 클래스 템플릿은 비동기 연산의 결과에 접근할 수 있는 메커니즘을 제공해요.

  • std::async, std::packaged_task 또는 std::promise를 통해 수행된 비동기 연산은 그 연산을 생성한 쪽에 std::future 객체를 제공할 수 있어요.
  • 비동기 연산을 생성한 쪽은 다양한 메서드를 사용해 std::future에서 값을 조회하거나 기다리거나 추출할 수 있어요. 이 메서드들은 비동기 연산이 아직 값을 제공하지 않았다면 블록될 수 있어요.
  • 비동기 연산이 결과를 생성한 쪽에 보낼 준비가 되면, 생성자의 std::future와 연결된 공유 상태를 수정하는 방식으로 결과를 전달할 수 있어요 (예: std::promise::set_value).

std::future는 공유 상태에 있는 결과에 대한 유일한 참조라는 점을 기억하세요. 즉, 결과가 다른 비동기 반환 객체와 공유되지 않아요. 결과에 대한 비유일 접근이 필요하다면 std::shared_future를 사용해야 해요.

멤버 함수

멤버 함수 설명
(constructor) future 객체를 생성해요. (public member function)
(destructor) future 객체를 소멸해요. (public member function)
operator= future 객체를 이동시켜요. (public member function)
share *this의 공유 상태를 shared_future로 전달하고 반환해요. (public member function)
결과 가져오기
get 결과를 반환해요. (public member function)
상태
valid future가 공유 상태를 가지고 있는지 확인해요. (public member function)
wait 결과를 사용할 수 있을 때까지 기다려요. (public member function)
wait_for 결과를 기다리되, 지정된 시간 초과 동안 사용할 수 없으면 반환해요. (public member function)
wait_until 결과를 기다리되, 지정된 시점이 될 때까지 사용할 수 없으면 반환해요. (public member function)

예제

#include <future>
#include <iostream>
#include <thread>

int main()
{
    // future from a packaged_task
    std::packaged_task<int()> task([]{ return 7; }); // wrap the function
    std::future<int> f1 = task.get_future(); // get a future
    std::thread t(std::move(task)); // launch on a thread

    // future from an async()
    std::future<int> f2 = std::async(std::launch::async, []{ return 8; });

    // future from a promise
    std::promise<int> p;
    std::future<int> f3 = p.get_future();
    std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach();

    std::cout << "Waiting..." << std::flush;
    f1.wait();
    f2.wait();
    f3.wait();
    std::cout << "Done!\nResults are: "
              << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    t.join();
}

출력:

Waiting...Done!
Results are: 7 8 9

예외가 있는 예제

#include <future>
#include <iostream>
#include <thread>

int main()
{
    std::promise<int> p;
    std::future<int> f = p.get_future();

    std::thread t([&p]
    {
        try
        {
            // code that may throw
            throw std::runtime_error("Example");
        }
        catch (...)
        {
            try
            {
                // store anything thrown in the promise
                p.set_exception(std::current_exception());
            }
            catch (...) {} // set_exception() may throw too
        }
    });

    try
    {
        std::cout << f.get();
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception from the thread: " << e.what() << '\n';
    }
    t.join();
}

출력:

Exception from the thread: Example

같이 보기

async (C++11) 함수를 비동기적으로 (잠재적으로 새 스레드에서) 실행하고 결과를 보관할 std::future를 반환해요. (function template)
shared_future (C++11) 비동기적으로 설정되는 값 (다른 future들이 참조할 수 있는) 을 기다려요. (class template)

더 알아보기 (Learn more)

cppreference