C++thread类探究

关thread 是C11新标准的类

介绍之前熟悉异常的使用也是很重要的

头文件exceptionstdexcpet是c++11处理异常的头文件

/*
	当我们通过throw返回异常的时候, 如果是线程的异常不能通过在主函数里面捕捉, 这样是捕捉不到的, 因为可能异常出现的时候主函数以及运行完毕了, 到时候没有接受到异常
	所以采用如下方法
*/
#include <thread>
#include <iostream>
#include <vector>
#include <mutex>
#include <exception>
#include <stdexcept>

using namespace std;

vector<exception_ptr> m_exception; //exception_ptr是用来存储当前异常消息的, 当前的异常消息通过current_exception()返回
mutex m_mutex;

void throw_fun()
{
    throw logic_error("throw_fun successful");//引起异常
}
void fun()
{
    try{
        
        throw_fun();
    }catch(exception& e)
    {
  		std::lock_guard<mutex> lock(m_mutex); 
    	m_exception.push_back(current_exception());//加入线程异常到队列
    }catch(...)
    {
        cout<<"catch except" <<endl;
    }
}
int main()
{
    m_exception.clear();
    vector<thread> th_vec;
    th_vec.clear();
    
    for(int i =0; i < 5; ++i)
    {
        th_vec.push_back(thread(fun));
        th_vec[i].join();//等待单个线程执行完毕, 然后释放执行下一个线程
        /*
        	thread tid[5];
        	这个类只有在初始化的时候才会赋初始值, 以后不能tid[i](fun);
        	可以使用上面这样插入信息或者是
        	thread tid[5];
        	tid[i] = thread(fun);
        	tid[i].join();
        */
    }
    
    for(auto& e : m_exception)
    {
        /*
        	NULL, 0, nullptr的区别
        	NULL在C++编译器是0,但是nullptr不是,所以我们调用NULL的时候会出现以下问题]
        	当函数重载的时候
        	void fun(int a)
            {
            
            }
            void fun(char *p)
            {
            
            }
            此时如果我们直接调用fun(NULL),会出现本来想调用第二个函数, 但是调用了第一个函数, 因为与第一个函数最匹配
        */
        try{
            if(e != nullptr)
            {
                rethrow_exception(e);//重新抛出异常
            }
        }catch(exception& e)
        {
            cout<<"exception caught:"<<e.what()<<"\n";
        }
    }
    
    cin.get();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值