250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/CPP] 19.05 Task base, async, future, promise 사용법 본문

C++/따배C++ 19강 모던 C++ 기능들

[C++/CPP] 19.05 Task base, async, future, promise 사용법

polarcompass 2021. 12. 15. 00:39
728x90
#include<iostream>
#include<future>
#include<thread>

using namespace std;

int main()
{
    // multi-threading
    {
        // 스코프를 넓게 잡고, 변수를 여러 쓰레드들이 공유하는 형태가
        // 일반적임.
        int result;
        std::thread t([&] {result = 1 + 2;});
        // thread를 기다리고 있음.
        t.join();
        cout << result << endl;
        // 결과 3
    }

    // task-based parallelism
    {
        // std::future<int> fut = ...
        auto fut = std::async([] {return 1 + 2;});
        // fut가 작업 끝날때까지 get()이 기다리고 있음.
        cout << fut.get() << endl;
    }

    // future and promise
    {
        std::promise<int> prom;
        auto fut = prom.get_future();

        auto t = std::thread([](std::promise<int>&& prom)
        {
            prom.set_value(1+2);
        }, std::move(prom));

        cout << fut.get() << endl;
        t.join();
    }

    // thread and async 중요한 차이점 하나
    // async는 소멸자가 끝날때까지 알아서 대기해준다.
    // 반면 thread는 join으로 기다려줘야함.

    {
        auto f1 = std::async([]{
            cout << "async1 start" << endl;
            this_thread::sleep_for(chrono::seconds(2));
            cout << "async1 end" << endl;
        });

        auto f2 = std::async([]{
            cout << "async2 start" << endl;
            this_thread::sleep_for(chrono::seconds(1));
            cout << "async2 end" << endl;
        });

        cout << "Main function" << endl;
    }

    // 앞에 f1, f2로 future로 받아줘야, multi threading이 실행됨.
    // future로 받지 않으면 순서대로 실행되는 일반적인 코드가됨.
    
    return 0;
}
728x90