引发异常时加入线程

时间:2019-02-25 19:41:37

标签: multithreading c++11 ubuntu exception arm

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

谢谢,约翰内斯

0 个答案:

没有答案