为什么这个简单的std::thread示例不起作用
Why does this simple std::thread example not work?
尝试了以下使用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
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(...)
也可以。
您需要链接到运行时库
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- std::thread在Linux Eclipse上不起作用
- std::thread在cygwin中工作,但在MinGw中不起作用
- 为什么这个简单的std::thread示例不起作用