shared_future๋ฅผ ์ฌ์ฉํ ์์
future, promise๋ ๊ธฐ๋ณธ์ ์ผ๋ก ํ์์ด๋ค.
ํ์ง๋ง promise์ ๊ฒฐ๊ณผ๋ฅผ ๋ค์์ future์์ ๊ณต์ ํ์ฌ ๊ฐ์ ํ์ฉํ ๊ฒฝ์ฐ๊ฐ ์๋ค.
์ด ๋ ์ฌ์ฉํ๋ ๊ฒ์ด shared_future.
#include <iostream>
#include <future>
#include <thread>
#include <vector>
using namespace std::chrono_literals;
void fn(std::shared_future<int> fut) {
std::cout << "num : " << fut.get() << std::endl;
}
int main()
{
std::promise<int> prms;
std::shared_future<int> fut = prms.get_future();
std::vector<std::thread> threads;
for (int i = 0; i < 3; ++i)
{
threads.emplace_back(fn, fut);
}
std::this_thread::sleep_for(1s);
prms.set_value(42);
for (auto& a : threads)
{
a.join();
}
}
๊ฒฐ๊ณผ๊ฐ
๋๊ธ