请任何人向我解释一下下面代码的输出,我很困惑线程是如何执行连接命令的,而不让主线程打印Hellos语句。
// example for thread::join
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::cout << "Spawning 3 threads...\n";
std::thread t1 (pause_thread,10);
std::thread t2 (pause_thread,5);
std::thread t3 (pause_thread,3);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
t1.join();
std::cout << "Hello 1!\n";
t2.join();
std::cout << "Hello 2!\n";
t3.join();
std::cout << "Hello 3!\n";
std::cout << "All threads joined!\n";
return 0;
}产出:
*Spawning 3 threads...
Done spawning threads. Now waiting for them to join:
pause of 3 seconds ended
pause of 5 seconds ended
pause of 10 seconds ended
Hello 1!
Hello 2!
Hello 3!
All threads joined!*非常感谢。
发布于 2014-03-14 19:48:20
join()阻塞直到线程完成。如果线程在调用join()之前完成,则随后的join()将立即返回。因此,当您将多个join()语句放在一个序列中时,您将在那里阻塞,直到所有线程完成为止,无论它们实际执行的顺序是什么。
请注意,join()阻止您从其中调用它的线程,而不是您调用它的线程。也就是说,在代码片段中,main()线程将等待,但t1、t2和t3将一直持续到它们完成。
https://stackoverflow.com/questions/22414188
复制相似问题