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

标签 c++ multithreading c++11

尝试使用 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

有人知道我错过了什么吗?

最佳答案

你必须加入 std::threads,就像你必须加入pthreads一样。

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

更新: This Debian bug report向我指出了解决方案:将 -pthread 添加到您的命令行。这很可能是一种解决方法,直到 std::thread 代码稳定并且 g++ 在它应该(或总是,对于 C++)拉入该库之前。

关于c++ - 为什么这个简单的 std::thread 示例不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6485705/

相关文章:

c# - 如何使用带有 IL2CPP 的纯 C++ 代码将 Unity 编译到 Windows 应用程序中?

java - Java 中 wait() 和 notifyAll() 的行为?

python - 运行 python 套接字服务器,如果远程关闭,则再次启动它监听

c++ - 对于对象图,我可以放置对象还是成对放置对象?

c++ - 这句话在 C++11 标准的第 §3.2/2 段中是什么意思?

c++ - 类型检查失败

c++ - SDL 输入有时只能工作

c++ - 在 float vector 中找到众数

Python多线程共享变量导致UnboundLocalError

c++ - 函数返回类型为父类时,如何返回子类的对象?