为什么这个简单的std :: thread示例不起作用?
试了用g++ -std=gnu++0x t1.cpp和g++ -std=c++0x t1.cpp编译的下面的例子,但是这两个都导致例子中止。 
 $ ./a.out terminate called after throwing an instance of 'std::system_error' what(): Aborted 
这是样本:
 #include <thread> #include <iostream> void doSomeWork( void ) { std::cout << "hello from thread..." << std::endl; return; } int main( int argc, char *argv[] ) { std::thread t( doSomeWork ); t.join(); return 0; } 
我试图在Ubuntu 11.04上:
 $ g++ --version g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2 
任何人都知道我错过了什么?
 你必须join std::thread ,就像你必须joinpthreads 。 
 int main( int argc, char *argv[] ) { std::thread t( doSomeWork ); t.join(); return 0; } 
  更新: 这个Debian的错误报告指出我的解决scheme:添加-pthread到你的命令行。 直到std::thread代码稳定下来,这很可能是一种解决方法,g ++在它应该(或者总是用于C ++)的时候将这个库拉进来。 
请在编译期间使用pthread库:g ++ -lpthread。
最简单的代码来重现该错误,以及如何解决:
把它放在一个名为s.cpp的文件中:
 #include <iostream> #include <stdlib.h> #include <string> #include <unistd.h> #include <thread> using namespace std; void task1(std::string msg){ cout << "task1 says: " << msg; } int main(){ std::thread t1(task1, "hello"); usleep(1000000); t1.detach(); } 
像这样编译:
 el@apollo:~/foo7$ g++ -os s.cpp -std=c++0x 
像这样运行,错误发生:
 el@apollo:~/foo7$ ./s terminate called after throwing an instance of 'std::system_error' what(): Operation not permitted Aborted (core dumped) 
要解决这个问题,请用-pthread标志像这样编译它:
 g++ -os s.cpp -std=c++0x -pthread ./s 
然后它正常工作:
 task1 says: hello 
对于它的价值,我有类似的代码使用g ++(MinGW)中的线程有不同的问题 。 解决方法是在创build线程和join线程之间进行一些“延迟”。
代码很less失败断言:
 std::atomic_bool flag{false}; std::thread worker( [&] () { flag.store(true); } ); worker.join(); assert(flag.load()); // Sometimes fails 
解决方法:
 std::atomic_bool flag{false}; std::thread worker( [&] () { flag.store(true); } ); while (not flag.load()) { std::this_thread::yield(); } worker.join(); assert(flag.load()); // Works fine 
 请注意yield()本身并没有帮助,因此while循环。 使用sleep_for(...)也可以。 
您需要链接到运行时库