shared_future
future와 promise는 1:1 매칭이 되어야하기 때문에 복사가 불가능하다. 하지만 promise를 통해 하나의 value가 set이 되면 이를 여러 곳에서 읽어야 하는 경우가 있을 수 있다. 여러 future에서 value를 읽어야하는 경우 Copy가 가능한 것이 shared_future이다.

Example Code : shared_future 사용
#include <iostream>
#include <chrono>
#include <future>
#include <thread>
#include <vector>
void fn(std::shared_future<int> fut)
{
std::cout << "num : " << fut.get() << std::endl;
}
int main()
{
using namespace std::chrono_literals;
std::promise<int> prms; // 데이터를 넣을 수 있는 promise 생성
std::shared_future<int> fut = prms.get_future(); // 연결될 shared_future 지정
std::vector<std::jthread> threads;
for (int i = 0; i < 5; i++)
{
threads.emplace_back(fn, fut);
}
std::this_thread::sleep_for(1s);
prms.set_value(42);
return 0;
}

5개의 thread에서 42가 출력된 것을 확인할 수 있다. 이처럼 shared_future는 future가 쓰이는 곳에서 copy가 필요할 때 사용할 수 있다. 예를 들어, std::async같은 경우 리턴 타입으로 future를 반환하는데 이 곳에 shared_future를 사용하면 copy가 가능한 future 타입의 오브젝트가 만들어지는 것이다.
'C++ > Thread (Async)' 카테고리의 다른 글
[Async] std::packaged_task (0) | 2022.08.14 |
---|---|
[Async] std::async (0) | 2022.08.14 |
[Async] Future, Promise (0) | 2022.08.10 |
[Async] 비동기 함수 Introduction (0) | 2022.08.10 |