๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์‹œ์Šคํ…œ๊ฐœ๋ฐœ/cplusplus

[๋น„๋™๊ธฐ] shared_future ์˜ˆ์ œ

by ์ด๋…ธํ‚ค_ 2022. 6. 16.

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();
    }
}

๊ฒฐ๊ณผ๊ฐ’

๋Œ“๊ธ€