c++多线程之join与detach函数

(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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值