c++多线程二 ---(复制和从新抛出异常)

这个建议看《c++高级编程》本书中的讲解,关于线程捕捉异常的问题,这里就不讲述了,直接上代码:

void doSomeWork()
{
	for (int i=0; i<5;i++)
	{
		cout << i << endl;
	}
	cout << "Thread throwing a runtime_error exception ..." << endl;
	throw runtime_error("Exception from thread");
}

void threadFunc(exception_ptr & err)
{
	try
	{
		doSomeWork();
	}
	catch (const std::exception&)
	{
		cout << "Thread caught exception,returning exception..." << endl;
		err = current_exception();
	}
}

void doWorkInThread()
{
	exception_ptr error;
	// Launch background thread	
	thread t{threadFunc, ref(error)};
	// wait for thread to finish
	t.join();
	//see if thread has thrown any exception
	if (error)
	{
		cout << "Main thread receive exception, rethrowing it ...." << endl;
		rethrow_exception(error);
	}
	else
	{
		cout << "Main thread did not receive any exception." << endl;
	}

}

void testdoWorkInThread()
{
	try
	{
		doWorkInThread();
	}
	catch (const std::exception& e)
	{
		cout << "Main function caught: '" <<e.what()<<" '" <<endl;
	}

}

输出结果:

0
1
2
3
4
Thread throwing a runtime_error exception ...
Thread caught exception,returning exception...
Main thread receive exception, rethrowing it ....
Main function caught: 'Exception from thread '

这就是线程的捕捉异常,通常情况下不应该阻塞join,在GUI中,同过发送消息,来在界面显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值