C++ Multithreading (2) -- joining/detaching threads

C++中的多线程处理,包括join和detach两个关键操作。join用于确保main函数等待所有worker线程执行完毕后再退出,而detach则解绑线程对象与线程函数,允许线程独立运行。不正确地使用join或detach可能导致运行时错误,因此使用时需要进行状态检查。为避免这种错误,可以采用RAII原则封装std::thread。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值