multithreading - 抛出异常时加入线程
问题描述
我正在使用 C++ 11 std::thread 库。抛出异常时在析构函数中加入线程是否有效?我的代码是:
#include <thread>
#include <stdio.h>
#include <exception>
#include <unistd.h>
class the_thread {
private:
std::thread t;
bool abort;
public:
the_thread();
~the_thread();
void run();
};
the_thread::the_thread()
{
abort = false;
t = std::thread(&the_thread::run, this);
#if 0
printf("before detach ...\n");
t.detach();
printf("after detach ...\n");
#endif
}
the_thread::~the_thread()
{
abort = true;
printf("destruct thread container\n");
if (t.joinable()) {
printf("into join\n");
t.join();
printf("out of join\n");
}
}
void the_thread::run()
{
int i;
i=0;
while (!abort) {
printf("hallo %d\n", i);
i++;
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
}
}
int run_thread_and_throw_exception(void)
{
the_thread t;
sleep(5);
throw std::runtime_error("some expected exception");
}
int main(int argc, char ** argv)
{
try {
run_thread_and_throw_exception();
} catch (const std::runtime_error &e) {
printf("exception %s caught\n", e.what());
}
return 0;
}
编译和运行时
gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
在我的 Ubuntu 16.04 开发机器上,此代码按预期运行:
bash$ ./thread_test
hallo 0
hallo 1
destruct thread container
into join
out of join
exception some expected exception caught
bash$
但是在编译时
arm-linux-gnueabi-g++ -Wall -g -O2 -std=c++11 -c -o main.o main.cpp
arm-linux-gnueabi-g++ -Wall -g -O2 -std=c++11 main.o -o thread_test -lpthread -static
(我们需要 -static 因为目标上没有 C++ 11 库)并在目标上运行它,会发生奇怪的事情:
bash-on-target# ./thread_test
hallo 0
hallo 1
destruct thread container
into join
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error 1082172112
Aborted
因此,析构函数中的联接似乎由于某种原因而失败。此外,当尝试分离线程时,分离立即失败:
bash-on-target# ./thread_test
before detach ...
terminate called without an active exception
hallo 0
hallo 0
Aborted
所以重复我的问题:在 C++11 中抛出异常时加入线程(并且可能正在休眠)是否有效?Ubuntu 16.04 附带的 ARM 的 C++ 11 库中是否可能存在错误?
ARM 工具链是:
bash$ arm-linux-gnueabi-g++ --version
arm-linux-gnueabi-g++ (Ubuntu/Linaro 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
谢谢和最美好的祝愿,约翰内斯
解决方案
推荐阅读
- typescript - 使用 TS 连接到在本地使用 terraform 创建的 ec2 实例
- list - 将列表传递给 get call Rest-Assured
- ios - 从城市名称获取地理位置
- python - 创建条形图但仅获得 TypeError 大小为 1 的数组可以转换为 Python 标量
- laravel - Laravel Livewire,表单提交:先做点事,然后提交表单
- python - 当我在 python 中制作 docker 图像时找不到导入的模块
- php - AJAX 按钮切换只工作一次,直到页面刷新
- excel - 从特定单元格开始图表,每当我插入新值时,它应该自动更新图表
- python - 在 Django Rest Framework 中通过 Vendor 的 Foregin 键获取所有项目
- android - 没有抛出这样的 Methoderror。方法 + 在 null 上被调用