본문 바로가기
시스템개발/cplusplus

[비동기] async 사용법 2

by 이노키_ 2022. 6. 16.

async 사용법 2

promise, future를 사용하는 것은 직관적이지 않을 경우가 있다.
get_future를 해야하고, set_value를 하기 때문에 return값은 void이다.
async를 이용해서 바꿔보자.

promise, future 스타일

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

using namespace std::chrono_literals;

void add(std::promise<int> prms, int n) {
    prms.set_value(n + 1);
}

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

    int num = 3;
    std::thread t(add, std::move(prms), num);

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

    t.join();
}

async, future 사용

int add(int n) {

    std::this_thread::sleep_for(2s);
//    throw std::runtime_error("yllee error");
    return n + 1;
}

int main()
{
    int num = 3;
    try {
        std::future<int> fut = std::async(add, num);
        int ret = fut.get();
        std::cout << "Ret : " << ret << std::endl;
    }
    catch (const std::exception& e)
    {
        std::cout << "exception : "<< e.what() << std::endl;
    }
}

위 두 예시 모두 결과값은
Ret : 4

댓글