Guest User

1~100까지 더하기를 async와 multi-thread로

a guest
Jun 16th, 2019
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <future>
  3. #include <thread>
  4. #include <chrono>
  5. #include <mutex>
  6. #include <atomic>
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11.     // 멀티 스레드: 1~100까지 더할건데, 1~50까지는 1번 스레드가, 51~100까지는 2번 스레드가 하게
  12.     {
  13.         int sum = 0;
  14.  
  15.         mutex mtx;
  16.        
  17.         auto sum_a_to_b = [&] (const int & a, const int & b) {
  18.             auto id = this_thread::get_id();
  19.             cout << id << " start\n";
  20.             for (int i = a; i <= b; i++)
  21.             {
  22.                 this_thread::sleep_for(std::chrono::milliseconds(1));
  23.                 scoped_lock lock(mtx);
  24.                 sum += i;
  25.             }
  26.             cout << id << " end\n";
  27.         };
  28.  
  29.         thread t1(sum_a_to_b, 1, 50);
  30.         thread t2(sum_a_to_b, 51, 100);
  31.        
  32.         t1.join();
  33.         t2.join();
  34.  
  35.         cout << sum << endl;
  36.     }
  37.  
  38.     // async 로 해보기
  39.     {
  40.         mutex mtx;
  41.         int sum = 0;
  42.         auto sum_a_to_b = [&](const int& a, const int& b) {
  43.             auto id = this_thread::get_id();
  44.             cout << id << " start\n";
  45.             for (int i = a; i <= b; i++)
  46.             {
  47.                 this_thread::sleep_for(std::chrono::milliseconds(1));
  48.                 scoped_lock lock(mtx);
  49.                 sum += i;
  50.             }
  51.             cout << id << " end\n";
  52.         };
  53.  
  54.         std::async(sum_a_to_b, 1, 50);
  55.         std::async(sum_a_to_b, 51, 100);
  56.  
  57.         cout << "1~100까지의 합: " << sum << endl;
  58.     }
  59.     // promise - future threading
  60.  
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment