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

[๋น„๋™๊ธฐ] promise, future ์‚ฌ์šฉ ์˜ˆ์ œ ๋ฐ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ์ƒํ™ฉ

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

promise, future๋ฅผ ์‚ฌ์šฉํ•œ ์˜ˆ์ œ

promise์™€ future๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ด ๋‘˜ ๊ฐ„์— ์ฑ„๋„์ด ์ƒ์„ฑ๋œ๋‹ค.
๋”ฐ๋ผ์„œ ์ด ์ฑ„๋„์€ ํ•˜๋‚˜๋งŒ ์œ ์ง€๋˜์–ด์•ผ ํ•œ๋‹ค.
์“ฐ๋ ˆ๋“œ๋กœ ์ธ์ž๋กœ promise๋ฅผ ๋„˜๊ธธ๋•Œ, ๋‹จ์ˆœํžˆ promise๋ฅผ ๋„˜๊ธฐ๋ฉด copyํ•œ๋‹ค๋Š” ๋œป์ด๋ฉฐ ์ด๋Š” 1:1์˜ ์ฑ„๋„ ๊ด€๊ณ„๊ฐ€ ์–ด๊ธ‹๋‚จ์„ ๋œปํ•œ๋‹ค.
๊ทธ๋ž˜์„œ std::move๋ฅผ ์ด์šฉํ•˜์—ฌ r-value๋กœ ์ธ์ž๋ฅผ ๋„˜๊ฒจ์ค€๋‹ค.

#include <iostream>
#include <future>
#include <thread>

using namespace std::chrono_literals;
void fn(std::promise<int> prm) {

    std::this_thread::sleep_for(2s);
    prm.set_value(33);
}

int main() {
    std::promise<int> prm;
    std::future<int> fut = prm.get_future();

    std::thread t(fn, std::move(prm));

    int num = fut.get();
    std::cout << "num : " << num << std::endl;

    t.join();
}

๊ฒฐ๊ณผ๊ฐ’

num : 33

์˜ˆ์™ธ ๋ฐœ์ƒ ์ƒํ™ฉ

set_value์™€ set_exception์„ ๋™์‹œ์— ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์—†๋‹ค.
thread์—์„œ๋Š” ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๊ธฐ๊ฐ€ ํž˜๋“ค๋‹ค๋Š” ์ด์Šˆ๊ฐ€ ์žˆ์œผ๋‚˜ promise, future๋กœ๋Š” ์ด๋ฅผ ํ•ธ๋“ค๋ง ํ•  ์ˆ˜ ์žˆ์Œ.

void fn(std::promise<int> prm) {

    std::this_thread::sleep_for(2s);
    try {
        throw std::runtime_error("yllee error");
        prm.set_value(33);
    }
    catch (...) {
        prm.set_exception(std::current_exception());
    }
    //set_value๊ณผ set_exception์„ ๋™์‹œ์— ์‚ฌ์šฉํ•ด์„œ๋Š” ์•ˆ๋œ๋‹ค.  
}

int main() {
    std::promise<int> prm;
    std::future<int> fut = prm.get_future();

    std::thread t(fn, std::move(prm));

    while (fut.wait_for(0.2s) != std::future_status::ready)
    {
        std::cout << "Doing another things... 0.2sec.... " << std::endl;
    }
    try {
        int num = fut.get();
        std::cout << "num : " << num << std::endl;
    }
    catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }

    t.detach();
}

๊ฒฐ๊ณผ๊ฐ’

๋Œ“๊ธ€