Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 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.     // async 예제: 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.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement