2012-04-09 47 views
3

我不知道我简单的std :: thread代码(下面列出)出了什么问题。在使用gcc 4.6或最新的4.7版本时,它总是崩溃。我用命令g++ -std=c++11 myfile.cppg++ -std=gnu++11 myfile.cpp编译它。在Linux上运行简单的std :: thread代码时使用gcc 4.6和4.7的核心转储

#include <iostream> 
#include <thread> 

using namespace std; 


void func() { 
    cout << "hello\n"; 
} 

int main() 
{ 
    std::thread thrd(func); 

    thrd.join(); 
} 

核心转储的调用堆栈是类似于下面

#0 0x00007ffff7539445 in raise() from /lib/x86_64-linux-gnu/libc.so.6 
    #1 0x00007ffff753cbab in abort() from /lib/x86_64-linux-gnu/libc.so.6 
    #2 0x00007ffff7b35b0d in __gnu_cxx::__verbose_terminate_handler()() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 
    #3 0x00007ffff7b33c16 in ??() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 
    #4 0x00007ffff7b33c43 in std::terminate()() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 
    #5 0x00007ffff7b33e6e in __cxa_throw() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 
    #6 0x00007ffff7b8829c in std::__throw_system_error(int)() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 
    #7 0x00007ffff7b89132 in std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>)() 
     from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 
    #8 0x000000000040118e in std::thread::thread<void (&)()> (this=0x7fffffffdeb0, __f= 
     @0x400e2c: {void (void)} 0x400e2c <func()>) at /usr/include/c++/4.7/thread:133 
    #9 0x0000000000400e5b in main() at main2.cpp:13 
+1

可能是一个[重复提问](http://stackoverflow.com/questions/6485705/why-does-this-simple-stdthread-example-not-work),请有测试解决方案是否正常工作。 – unsym 2012-04-09 23:27:16

回答

5

您可以选择使用-pthread选项编译。

g++ -std=c++11 -pthread -o main main.cpp 
+0

谢谢。是的,它现在使用'-pthread'后就可以工作。 – Derek 2012-04-12 20:28:01

+0

@Derek很高兴它的工作。请注意,您可以通过点击投票按钮下方的绿色标记来接受答案。 – inf 2012-04-12 20:45:53