(1)当使用join()函数时,主调线程(main函数里有一个主调线程)阻塞,等待被调线程终止,然后主调线程回收被调线程资源,并继续运行;上面这段话的意思就是,使用join(),线程运行完,main函数才能结束。
(2)当使用detach()函数时,主调线程继续运行,被调线程驻留后台运行,主调线程无法再取得该被调线程的控制权。当主调线程结束时,由运行时库负责清理与被调线程相关的资源。上面这段话的意思就是,使用detach(),main函数不用等待线程结束才能结束。有时候线程还没运行完,main函数就已经结束了。
#include <iostream>
#include <thread>
#include <algorithm>
#include<vector>
class WorkerThread {
public:
void operator()() {
std::cout << "Worker Thread " << std::this_thread::get_id() << "is Executing" << std::endl;
}
};
int main(void) {
std::vector<std::thread> threadList;
//创建10个工作线程
for (int i = 0; i < 10; i++) {
threadList.push_back(std::thread(WorkerThread()));
}
// 等待所有的工作线程结束,即对每一个 std::thread 对象调用 join() 函数
std::cout << "wait for all the worker thread to finish" << std::endl;
std::for_each(threadList.begin(), threadList.end(), std::mem_fn(&std::thread::join));
// 不等待所有的工作线程结束,即对每一个 std::thread 对象调用 detach() 函数
//std::for_each(threadList.begin(), threadList.end(), std::mem_fn(&std::thread::detach));
// 下面这条语句是最后打印的
std::cout << "Exiting from Main Thread" << std::endl;
system("pause");
return 0;
}