std::future
cppreference.com
<tbody>
</tbody>
| <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와 연결된 공유상태(shared state)-예컨데std::promise::set_value-를 변경하여 생성 주체에게 그 결과를 전달한다.
참고로 std::future는 다른 비동기 반환 객체와 공유되지 않는 공유 상태를 참조한다(std::shared_future의 동작방식은 다르다.)
멤버 함수
| constructs the future object (public member function) | |
| destructs the future object (public member function) | |
| moves the future object (public member function) | |
transfers the shared state from *this to a shared_future and returns it (public member function) | |
Getting the result | |
| returns the result (public member function) | |
State | |
| checks if the future has a shared state (public member function) | |
| waits for the result to become available (public member function) | |
| waits for the result, returns if it is not available for the specified timeout duration (public member function) | |
| waits for the result, returns if it is not available until specified time point has been reached (public member function) | |
예제
코드 실행
#include <iostream>
#include <future>
#include <thread>
int main()
{
// packaged_task 의 future 객체
std::packaged_task<int()> task([](){ return 7; }); // 함수 래퍼
std::future<int> f1 = task.get_future(); // future 얻기
std::thread(std::move(task)).detach(); // 쓰레드 실행
// an 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( [](std::promise<int> p){ p.set_value_at_thread_exit(9); },
std::move(p) ).detach();
std::cout << "Waiting..." << std::flush;
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: "
<< f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
}
Output:
Waiting...Done!
Results are: 7 8 9
See also
(C++11) |
runs a function asynchronously (potentially in a new thread) and returns a std::future that will hold the result (function template) |
(C++11) |
waits for a value (possibly referenced by other futures) that is set asynchronously (class template) |