C++ future

2021. 3. 30. 00:05·C++/Library

future

  • <future> 라이브러리

  • <future> 라이브러리에 <thread> 라이브러리가 포함되어 있다.

    <future>

    #include <chrono>
    #include <condition_variable>
    #include <functional>
    #include <memory>
    #include <mutex>
    #include <ppltasks.h>
    #include <system_error>
    #include <thread>
    #include <utility>

예제

  • 쓰레드 예제와 이를 future, async로 적용한 예제

    #include <iostream>
    #include <future>
    
    int         main()
    {
        using namespace std;
    
        {
            int result;
    
            thread t([&] { result = 1 + 2; });
            t.join();
            cout << result << endl;
        }
    
        {
            auto fut = std::async([] { return 1 + 2; });
    
            cout << fut.get() << endl;
        }
    }
    
    /* stdout stderr
    3
    3
    */
  • thread를 통해 future를 사용하려면 promise가 필요하다.

    • promise.set_value()가 호출되면 promise 객체가 자신의 future 객체에게 값을 전달하고, future.get() 함수를 통해 기다렸다가 값을 받을 수 있다. (내부적으로 wait 함수가 기다린다.)

      • https://modoocode.com/284
      #include <iostream>
      #include <future>
      
      int         main()
      {
          using namespace std;
      
          std::promise<int> prom;
          auto fut = prom.get_future();
      
          auto t = thread([](std::promise<int>&& prom)
              {
                  prom.set_value(1 + 2);
              }, std::move(prom));
      
          cout << fut.get() << endl;
          t.join();
      }
      
      /* stdout stderr
      3
      */
  • async와 thread는 처리하는 방식이 다르다..는데

    • 강의에서는 출력되는 순서가 다른데, 내 컴퓨터에서는 똑같다.

      #include <iostream>
      #include <future>
      
      int         main()
      {
          using namespace std;
      
          auto f1 = std::async([] {
              cout << "async1 start\n";
              this_thread::sleep_for(chrono::seconds(2));
              cout << "async1 end\n";
              });
      
          auto f2 = std::async([] {
              cout << "async2 start\n";
              this_thread::sleep_for(chrono::seconds(1));
              cout << "async2 end\n";
              });
      
          cout << "Main function\n";
      }
      
      /* stdout stderr
      Main function
      async1 start
      async2 start
      async2 end
      async1 end
      */
      #include <iostream>
      #include <future>
      
      int         main()
      {
          using namespace std;
      
          auto f1 = std::thread([] {
              cout << "thread1 start" << endl;
              this_thread::sleep_for(chrono::seconds(2));
              cout << "thread1 end" << endl;
              });
      
          auto f2 = std::thread([] {
              cout << "thread2 start" << endl;
              this_thread::sleep_for(chrono::seconds(1));
              cout << "thread2 end" << endl;
              });
      
          cout << "Main function" << endl;
          f1.join();
          f2.join();
      }
      
      /* stdout stderr
      Main function
      thread1 start
      thread2 start
      thread2 end
      thread1 end
      */
  • async는 반환 값을 받는 변수가 없으면 멀티 쓰레딩 기능이 작동하지 않는다.

    #include <iostream>
    #include <future>
    
    int         main()
    {
        using namespace std;
    
        std::async([] {
            cout << "async1 start" << endl;
            this_thread::sleep_for(chrono::seconds(2));
            cout << "async1 end" << endl;
            });
    
        std::async([] {
            cout << "async2 start" << endl;
            this_thread::sleep_for(chrono::seconds(1));
            cout << "async2 end" << endl;
            });
    
        cout << "Main function" << endl;
    }
    
    /* stdout stderr
    async1 start
    async1 end
    async2 start
    async2 end
    Main function
    */
저작자표시 (새창열림)

'C++ > Library' 카테고리의 다른 글

C++ forward  (0) 2021.03.30
C++ 멀티쓰레딩 (Multithreading)  (0) 2021.03.30
C++ atomic  (0) 2021.03.30
C++ mutex  (0) 2021.03.30
C++ 파일 임의 위치 접근  (0) 2021.03.29
'C++/Library' 카테고리의 다른 글
  • C++ forward
  • C++ 멀티쓰레딩 (Multithreading)
  • C++ atomic
  • C++ mutex
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 분류 전체보기 (317)
      • Algorithm (13)
        • 알기 쉬운 알고리즘 (10)
        • Search (1)
        • Sort (2)
      • Arduino (0)
      • C++ (185)
        • Class (46)
        • Exception (6)
        • Library (51)
        • Overloading (10)
        • SmartPointer (5)
        • Syntax (33)
        • TBC++ (23)
        • Templates (9)
        • VisualStudio (2)
      • Embedded (1)
      • Git (4)
      • Java (5)
      • Linux (16)
        • Error (1)
        • Linux Structure (11)
      • MacOS (7)
      • OS (1)
        • Concurrency (1)
      • Python (21)
        • Class (1)
        • Function (2)
        • Syntax (17)
      • Raspberrypi (9)
      • Review (1)
      • Utility (12)
        • VSCode (5)
        • VirtualBox (3)
      • Web (8)
        • Nginx (1)
        • React (3)
        • Django (1)
      • Windows (20)
        • Registry (3)
        • WSL (1)
        • DeviceDriver (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    제외
    윈도우
    Solaris 10
    windows
    dism
    SFC
    SunOS 5.1
    시스템 복구
    citrix workspace
    맥북 카카오톡 알림 안뜸
    vscode
    알림
    스프링 프레임워크 핵심 기술
    Windows 11
    MacOS
    java
    EXCLUDE
    KakaoTalk
    unix
    로지텍 마우스 제스처
    윈도우 명령어
    그림판
    백기선
    mspaint
    스프링
    Workspace
    logi options
    spring
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ future
상단으로

티스토리툴바