在c++里,如果在Thread中有未捕获的异常,那么gcc会主动catch该异常,从而导致函数栈中无有用的信息。

下面是一个例子

#include <stdexcept>
#include <thread>
void foo()
{
throw std::runtime_error("foo");
}

void subroutine() {
std::thread t(foo);
t.join();
}

int main()
{
std::thread t(subroutine);
t.join();
}


这里仅仅指的是c++中定义的异常,以及子类;如果是错误,比如说除以零,这种是可以直接抛出来的


使用编译命令

g++ -Wall -std=c++0x -g tmp.cpp

然后使用gdb执行

gdb a.out

(gdb) r
Using host libthread_db library "/lib64/libthread_db.so.1".
[New Thread 0x7ffff7dc1700 (LWP 2427)]
terminate called after throwing an instance of 'std::runtime_error'
what(): foo

运行bt调出函数栈信息,发现没有有效的内容

Program received signal SIGABRT, Aborted.
[Switching to Thread 0x7ffff7dc1700 (LWP 2427)]
0x00000034906362a5 in raise () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install
boost-thread-1.47.0-3.fc16.x86_64 glibc-2.14.90-14.x86_64
libgcc-4.6.2-1.fc16.x86_64 libstdc++-4.6.2-1.fc16.x86_64
(gdb) bt
#0 0x00000034906362a5 in raise () from /lib64/libc.so.6
#1 0x0000003490637bbb in abort () from /lib64/libc.so.6
#2 0x000000349aabbf8d in __gnu_cxx::__verbose_terminate_handler()
() from /usr/lib64/libstdc++.so.6
#3 0x000000349aaba146 in ?? () from /usr/lib64/libstdc++.so.6
#4 0x000000349aaba173 in std::terminate() () from
/usr/lib64/libstdc++.so.6
#5 0x000000349aa70bdb in ?? () from /usr/lib64/libstdc++.so.6
#6 0x0000003490a07d90 in start_thread () from /lib64/libpthread.so.0
#7 0x00000034906eeddd in clone () from /lib64/libc.so.6

解决方案

  1. 改用boost::thread
#include <stdexcept>
#include <thread>
void foo()
{
throw std::runtime_error("foo");
}

void subroutine() {
boost::thread t(foo);
t.join();
}

int main()
{
boost::thread t(subroutine);
t.join();
}
  1. 改用pthread
#include <stdexcept>
//#include <thread>
void *foo(void *)
{
throw std::runtime_error("foo");
}

void *subroutine(void *a) {
pthread_t thread_id;
pthread_create(&thread_id, NULL, foo, NULL);
pthread_join(thread_id,NULL);

return NULL;
}

int main()
{
pthread_t thread_id;
pthread_create(&thread_id, NULL, subroutine, NULL);
pthread_join(thread_id,NULL);

return 0;
}

这时的函数栈可以显示到对应的crash函数了

#0  0x00007f1b7840b1f7 in raise () from /lib64/libc.so.6
#1 0x00007f1b7840c8e8 in abort () from /lib64/libc.so.6
#2 0x00007f1b78d11a95 in __gnu_cxx::__verbose_terminate_handler() ()
from /lib64/libstdc++.so.6
#3 0x00007f1b78d0fa06 in ?? () from /lib64/libstdc++.so.6
#4 0x00007f1b78d0fa33 in std::terminate() () from /lib64/libstdc++.so.6
#5 0x00007f1b78d0fc53 in __cxa_throw () from /lib64/libstdc++.so.6
#6 0x00000000004007bb in foo ()
at main.cpp:5
#7 0x00007f1b78fc0e25 in start_thread () from /lib64/libpthread.so.0
#8 0x00007f1b784ce34d in clone () from /lib64/libc.so.6

  1. 按照​​这里​​介绍的在函数上使用noexcept修饰 (但是好像不行)
  2. 更换未gcc8

参考链接




  1. https://gcc.gnu.org/legacy-ml/gcc-help/2011-11/msg00140.html​
  2. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55917​
  3. https://zhuanlan.zhihu.com/p/59554240​