如何在clang中使用boost_threads?

时间:2015-04-24 19:01:09

标签: c++ boost clang boost-thread clang++

我在使用带有clang的bo​​ost_threads时遇到问题。新版Ubuntu 15.04的clang版本为3.6.0,升级版本为1.55.0。曾经与以前版本的clang一起使用的程序现在是启动时的段错误。当我使用g ++时没有问题。

这是一个示例程序来说明这一点。

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

void output() {
  try {
    int x = 0;
    for (;;) {
      boost::this_thread::sleep(boost::posix_time::milliseconds(100));
      cerr << x++ << endl;
    }
  } catch (boost::thread_interrupted&) {}
}

int main(int argc, char* argv[]) {
  try {
    boost::thread output_worker(output);
    boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
    output_worker.interrupt();
    output_worker.join();
  } catch (...) {
    cerr << "Unexpected error!" << endl;
    exit(1);
  }
}

如果我用g ++编译它就可以了,即

g++ thread.cpp -lboost_thread -lboost_system

如果我用clang编译它

clang++ thread.cpp -lboost_thread -lboost_system

我使用下面的gdb跟踪获得了段错误

Starting program: /home/dejan/test/a.out 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bd0580 in boost::exception_ptr boost::exception_detail::get_static_exception_object<boost::exception_detail::bad_alloc_>() ()
   from /usr/lib/x86_64-linux-gnu/libboost_thread.so.1.55.0
(gdb) bt
#0  0x00007ffff7bd0580 in boost::exception_ptr boost::exception_detail::get_static_exception_object<boost::exception_detail::bad_alloc_>() ()
   from /usr/lib/x86_64-linux-gnu/libboost_thread.so.1.55.0
#1  0x00007ffff7bcb16a in ?? () from /usr/lib/x86_64-linux-gnu/libboost_thread.so.1.55.0
#2  0x00007ffff7de95ba in call_init (l=<optimized out>, argc=argc@entry=1, argv=argv@entry=0x7fffffffdf98, env=env@entry=0x7fffffffdfa8)
   at dl-init.c:72
#3  0x00007ffff7de96cb in call_init (env=<optimized out>, argv=<optimized out>, argc=<optimized out>, l=<optimized out>) at dl-init.c:30
#4  _dl_init (main_map=0x7ffff7ffe188, argc=1, argv=0x7fffffffdf98, env=0x7fffffffdfa8) at dl-init.c:120
#5  0x00007ffff7dd9d0a in _dl_start_user () from /lib64/ld-linux-x86-64.so.2
#6  0x0000000000000001 in ?? ()
#7  0x00007fffffffe2fe in ?? ()
#8  0x0000000000000000 in ?? ()

我做错了吗?

1 个答案:

答案 0 :(得分:1)

使用clang -std=c++11进行编译会使boost更改其内部实现并实际解决分段错误。 它不是一个理想的解决方案,但它是我将使用我们的代码的方式。