Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <future>
- #include <thread>
- #include <chrono>
- #include <mutex>
- #include <atomic>
- using namespace std;
- int main()
- {
- // async 예제: 1~100까지 더할건데, 1~50까지는 1번 스레드가, 51~100까지는 2번 스레드가 하게
- {
- int sum = 0;
- mutex mtx;
- auto sum_a_to_b = [&] (const int & a, const int & b) {
- auto id = this_thread::get_id();
- cout << id << " start\n";
- for (int i = a; i <= b; i++)
- {
- this_thread::sleep_for(std::chrono::milliseconds(1));
- scoped_lock lock(mtx);
- sum += i;
- }
- cout << id << " end\n";
- };
- thread t1(sum_a_to_b, 1, 50);
- thread t2(sum_a_to_b, 51, 100);
- t1.join();
- t2.join();
- cout << sum << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement