voidfooWithTime(int n_seconds, std::string name){ for (int i = 0; i < n_seconds; i++) { usleep(1000); std::cout << name <<" Thread: worked for " << i + 1 << " seconds.." << std::endl; } }
intmain(){
std::thread t1(fooWithTime, 5, "Child");
fooWithTime(3, "Main");
t1.join();
std::cout << "Main thread exit! " << std::endl;
return0; }}
由于在 main 函数最后加入 t1.join() 所以在主函数输出 3 秒之后会等到 子线程工作完返回时才退出,输出如下:
1 2 3 4 5 6 7 8 9
Main Thread: worked for 1 seconds.. Child Thread: worked for 1 seconds.. Main Thread: worked for 2 seconds.. Child Thread: worked for 2 seconds.. Main Thread: worked for 3 seconds.. Child Thread: worked for 3 seconds.. Child Thread: worked for 4 seconds.. Child Thread: worked for 5 seconds.. Main thread exit!
如果把 t1.join() 去掉之后,输出如下:
1 2 3 4 5 6 7 8
Main Thread: worked for 1 seconds.. Child Thread: worked for 1 seconds.. Child Thread: worked for 2 seconds.. Main Thread: worked for 2 seconds.. Child Thread: worked for 3 seconds.. Main Thread: worked for 3 seconds.. Main thread exit! terminate called without an active exceptionn
voidfooWithTime(int n_seconds, std::string name){ for (int i = 0; i < n_seconds; i++) { usleep(1000); std::cout << name <<" Thread: worked for " << i + 1 << " seconds.." << std::endl; } }
Main Thread: worked for 1 seconds.. Child Thread: worked for 1 seconds.. Main Thread: worked for 2 seconds.. Child Thread: worked for 2 seconds.. Main Thread: worked for 3 seconds.. Main thread exit!
voidfooWithTime(int n_seconds, std::string name){ for (int i = 0; i < n_seconds; i++) { usleep(1000); std::cout << name <<" Thread: worked for " << i + 1 << " seconds.." << std::endl; } }