Namespaces
Variants

std:: future

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
future
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
헤더 파일에 정의됨 <future>
template < class T > class future ;
(1) (C++11부터)
template < class T > class future < T & > ;
(2) (C++11부터)
template <> class future < void > ;
(3) (C++11부터)

클래스 템플릿 std::future 는 비동기 연산의 결과에 접근하기 위한 메커니즘을 제공합니다:

  • 비동기 연산의 생성자는 이후 다양한 방법을 사용하여 std::future 에서 값을 조회하거나, 대기하거나, 추출할 수 있습니다. 이러한 메서드들은 비동기 연산이 아직 값을 제공하지 않은 경우 블로킹될 수 있습니다.
  • 비동기 연산이 생성자에게 결과를 보낼 준비가 되면, 생성자의 std::future 와 연결된 shared state (예: std::promise::set_value )를 수정함으로써 이를 수행할 수 있습니다.

std::future 는 다른 비동기 반환 객체와 공유되지 않는 공유 상태를 참조한다는 점에 유의하십시오 ( std::shared_future 와 대비됨).

목차

멤버 함수

future 객체를 생성합니다
(public member function)
future 객체를 소멸합니다
(public member function)
future 객체를 이동합니다
(public member function)
* this 의 공유 상태를 shared_future 로 전송하고 반환합니다
(public member function)
결과 얻기
결과를 반환합니다
(public member function)
상태
future가 공유 상태를 가지고 있는지 확인합니다
(public member function)
결과가 사용 가능해질 때까지 대기합니다
(public member function)
결과를 대기하며, 지정된 시간 제한 동안 사용 가능하지 않으면 반환합니다
(public member function)
결과를 대기하며, 지정된 시간 점에 도달할 때까지 사용 가능하지 않으면 반환합니다
(public member function)

예제

#include <future>
#include <iostream>
#include <thread>
int main()
{
    // packaged_task로부터 생성된 future
    std::packaged_task<int()> task([]{ return 7; }); // 함수를 래핑
    std::future<int> f1 = task.get_future(); // future 획득
    std::thread t(std::move(task)); // 스레드에서 실행
    // async()로부터 생성된 future
    std::future<int> f2 = std::async(std::launch::async, []{ return 8; });
    // promise로부터 생성된 future
    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
        {
            // 예외를 발생시킬 수 있는 코드
            throw std::runtime_error("Example");
        }
        catch (...)
        {
            try
            {
                // promise에 발생한 모든 예외 저장
                p.set_exception(std::current_exception());
            }
            catch (...) {} // set_exception()도 예외를 발생시킬 수 있음
        }
    });
    try
    {
        std::cout << f.get();
    }
    catch (const std::exception& e)
    {
        std::cout << "스레드에서 발생한 예외: " << e.what() << '\n';
    }
    t.join();
}

출력:

스레드에서 발생한 예외: Example

참고 항목

(C++11)
함수를 비동기적으로(새 스레드에서 실행될 수 있음) 실행하고 결과를 담을 std::future 를 반환함
(함수 템플릿)
비동기적으로 설정되는 값(다른 future들이 참조할 수 있음)을 기다림
(클래스 템플릿)