Joining/Detaching threads
join threads
当在main()函数中创建了线程t1,如果不使用t1.join(),那么main就有可能在t1结束前,就先结束退出了,然后就会报错(报错原因见下文):
#include <iostream>
#include <thread>
using namespace std;
void func(){
cout << "t1 is executing "<< endl;
}
int main(){
std::thread t1(func);
cout << "main is executing " << endl;
}
-------------------------------OUTPUT-----------------------------------------
t1 is executing
main is executing
terminate called without an active exception
Aborted (core dumped)
假如我们在main里创建了很多worker threads,如果要让main thread等到所有worker threads都结束之后才结束,那么就要在main里调用join():
#include <iostream>
#include <thread>
#include <vector>
#include <functional> // for std::mem_fn
void worker