[英]std::thread created thread not handling exceptions
我正在创建一些将分离的std :: threads。 我想让它们运行很长时间,并希望它们自己处理异常。
我使用std :: thread(Function)创建了一个线程,并在释放互斥锁之前调用了detach,其中Function执行以下操作:
void BlockStart() noexcept {
std::lock_guard<std::mutex> sync(lock);
}
void Function()
{
BlockStart();
try
{
throw;
}
catch(...)
{
std::cerr << "Caught something...\n";
}
}
每次我运行此代码时,都不会调用异常处理程序。 调用std :: terminate()的默认处理程序,该处理程序调用abort。
我如何获得std :: thread启动线程来处理异常?
基于此问题的答案: https : //stackoverflow.com/a/5378736/1619294
如果你
throw;
单独运行,并且当前没有异常可以重新抛出,然后程序突然结束。 (更具体地说,调用terminate()
。)
您可能想要做类似的事情
void Function()
{
try
{
SomeOtherFunction();
}
catch(...)
{
std::cerr << "Caught something...\n";
}
}
另外,请注意, BlockStart()
函数中的锁定防护+互斥锁只会在函数的持续时间内阻塞,并且在返回后将不会持续存在。 解决方案是在Function()
内设置锁卫锁
void Function() {
std::lock_guard<std::mutex> sync(lock);
...
单独调用throw
会重新引发当前异常,但这仅在catch
块内部调用时有效。 如果您在没有当前异常的情况下try
在try
块内自行调用throw
,则会调用terminate()
并导致应用程序死亡。 你必须告诉throw
什么的里面时抛出try
块,如:
void Function()
{
BlockStart();
try
{
throw std::runtime_error("something bad happened");
}
catch(const std::exception& e)
{
std::cerr << "Caught something... " << e.what() << std::endl;
}
}
同样,在BlockStart()
内使用std::lock_guard
是没有用的。 sync
是一个局部变量,因此它将超出范围并在BlockStart()
退出时释放互斥BlockStart()
。 只有在互斥锁被锁定时实际上执行了某些操作时,才有意义使用它,例如:
void BlockStart() noexcept
{
std::lock_guard<std::mutex> sync(lock);
// do something here while the mutex is locked...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.