Boost :: thread: Segfault when running the optimized version

I have problems with work boost:thread. It works great when compiling without optimization:

g++ -o test-thread test-thread.cpp -lboost_thread-gcc-mt-s -lpthread
./test-thread

But the version that is combined with the optimizations fails

g++ -O2 -o test-thread test-thread.cpp -lboost_thread-gcc-mt-s -lpthread
./test-thread
Segmentation fault

Does anyone know what the reason is?

Here is the code I'm using:

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

void task1() {
  // do something
}
void task2() {
  // do something
}

int main (int argc, char ** argv) {
  using namespace boost;

  function0<void> f1(&task1);
  function0<void> f2(&task2);

  thread thread_1(f1);
  thread thread_2(f2);

  // do other stuff 
  thread_2.join();
  thread_1.join();
  return 0;
}

PS: I am using boost 1.32 on ubuntu linux.

UPDATE:

This is where it crashes in the debugger (where line 37 is the number c thread_2.join();in my source code):

(gdb) bt
#0  0x080499e0 in boost::thread::join ()
#1  0x080496b8 in main (argc=1, argv=0xbfea3eb4) at ../src/test-thread.cpp:37

Here are my actual two functions:

void task1() {
  std::cerr << "THREAD 1 START" << std::endl;
  for(double i=0; i<999999; ++i){
    std::cout << i << std::endl;
  }
  std::cerr << "THREAD 1 END" << std::endl;
}

void task2() {
  std::cerr << "THREAD 2 START" << std::endl;
  for(double i=0; i<999999; ++i){
    std::cout << i << std::endl;
  }
  std::cerr << "THREAD 2 END" << std::endl;
}

Thanks for any help!

+3
source share
2 answers

I found a mistake! I contacted the wrong version of the library. I used boost_thread-gcc-mt-s, but it works with boost_thread-gcc-mtinstead:

g++ -O2 -o test-thread test-thread.cpp -lboost_thread-gcc-mt -lpthread

, , . boost_thread-gcc-mt-d, , , , , segfault -g. , , .

+2

, (ulimit -c unlimited), (-O2 -g), gdb? (gdb test-thread core, backtrace gdb, quit, )

UPDATE

, boost::thread::join. โ€‹โ€‹:

  • boost::thread::join:
    • disassemble boost::thread::join
    • disassemble
  • :
    • info registers

boost::thread::join ( 1.32 ) , , Ubuntu (, , ), .

, ?

void thread::join()
{
    int res = 0;
#if defined(BOOST_HAS_WINTHREADS)
    res = WaitForSingleObject(reinterpret_cast<HANDLE>(m_thread), INFINITE);
    assert(res == WAIT_OBJECT_0);
    res = CloseHandle(reinterpret_cast<HANDLE>(m_thread));
    assert(res);
#elif defined(BOOST_HAS_PTHREADS)
    res = pthread_join(m_thread, 0);
    assert(res == 0);
#elif defined(BOOST_HAS_MPTASKS)
    OSStatus lStatus = threads::mac::detail::safe_wait_on_queue(
        m_pJoinQueueID, NULL, NULL, NULL, kDurationForever);
    assert(lStatus == noErr);
#endif
    // This isn't a race condition since any race that could occur would
    // have us in undefined behavior territory any way.
    m_joinable = false;
}

:

  • , , volatile
  • / ( ), ,
+3

Source: https://habr.com/ru/post/1703607/


All Articles