voidf1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 1 executing\n"; ++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'; }
1 2 3 4 5 6 7 8 9 10 11
Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Final value of n is 5
voidis_main_thread(){ if ( main_thread_id == std::this_thread::get_id() ) std::cout << "This is the main thread.\n"; else std::cout << "This is not the main thread.\n"; }
voidpause_thread(int n) { std::this_thread::sleep_for (std::chrono::seconds(n)); std::cout << "pause of " << n << " seconds ended\n"; }
intmain() { std::cout << "Spawning 3 threads...\n"; std::thread t1(pause_thread,1); std::thread t2(pause_thread,2); std::thread t3(pause_thread,3); std::cout << "Done spawning threads. Now waiting for them to join:\n"; t1.join(); t2.join(); t3.join(); std::cout << "All threads joined!\n";
return0; }
Output (after 3 seconds):
1 2 3 4 5 6
Spawning 3 threads... Done spawning threads. Now waiting for them to join: pause of 1 seconds ended pause of 2 seconds ended pause of 3 seconds ended All threads joined!
std::cout << "(the main thread will now pause for 5 seconds)\n"; // give the detached threads time to finish (but not guaranteed!): pause_thread(5); return0; }
Output:
1 2 3 4 5 6 7
Spawning and detaching 3 threads... Done spawning threads. (the main thread will now pause for 5 seconds) pause of 1 seconds ended pause of 2 seconds ended pause of 3 seconds ended pause of 5 seconds ended