首页 > 解决方案 > 抛出异常时加入线程

问题描述

我正在使用 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.

谢谢和最美好的祝愿,约翰内斯

标签: multithreadingc++11ubuntuexceptionarm

解决方案


推荐阅读