为什么这个简单的std::thread示例不起作用

Why does this simple std::thread example not work?

本文关键字:thread 不起作用 std 简单 为什么      更新时间:2023-10-16

尝试了以下使用g++ -std=gnu++0x t1.cppg++ -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 s,就像您必须加入pthreads一样。

int main( int argc, char *argv[] )
{
    std::thread t( doSomeWork );
    t.join();
    return 0;
}

更新:这个Debian错误报告向我指出了解决方案:将-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++ -o s 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)

要修复它,请使用-phread标志如下编译:

g++ -o s s.cpp -std=c++0x -pthread
./s

然后它工作正常:

task1 says: hello

值得一提的是,我有不同的问题,类似的代码使用g++(MinGW)中的线程。解决方法是在创建线程和加入线程之间设置一些"延迟"

断言很少失败的代码:

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(...)也可以。

您需要链接到运行时库