std::cout << "increase global counter with 10 threads...\n"; for (int i=1; i<=10; ++i) threads.push_back(std::thread(increase_global,1000));
std::cout << "increase counter (foo) with 10 threads using reference...\n"; std::atomic<int> foo(0); for (int i=1; i<=10; ++i) threads.push_back(std::thread(increase_reference,std::ref(foo),1000));
std::cout << "increase counter (bar) with 10 threads using member...\n"; C bar; for (int i=1; i<=10; ++i) threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));
std::cout << "synchronizing all threads...\n"; for (auto& th : threads) th.join();
voidf1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread " << n << " executing\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }
voidf2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }
intmain() { int n = 0; std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread t2.join(); t4.join(); std::cout << "Final value of n is " << n << '\n'; return0; }