关thread 是C11新标准的类
介绍之前熟悉异常的使用也是很重要的
头文件exception
和 stdexcpet
是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;
}