为什么这个简单的std :: thread示例不工作? [英] Why does this simple std::thread example not work?

查看:104
本文介绍了为什么这个简单的std :: thread示例不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 g ++ -std = gnu ++ 0x t1.cpp g ++ -std = c ++ 0x t1编译的以下示例。 cpp ,但这两个都会导致示例中止。

  $ ./a.out 
终止调用'std :: system_error'的实例
what():
中止

以下是示例:

  #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



任何人都知道我错过了什么?

解决方案

p>你必须加入 std :: thread ,就像你必须加入 pthreads

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

UPDATE: 此Debian错误报告指向我的解决方案:add -pthread 到你的命令行。这很可能是一个解决方法,直到 std :: thread 代码稳定,g ++拉动该库在它应该(或总是,对于C ++)。


Tried the following example compiled with g++ -std=gnu++0x t1.cpp and g++ -std=c++0x t1.cpp but both of these result in the example aborting.

$ ./a.out 
terminate called after throwing an instance of 'std::system_error'
  what():  
Aborted

Here is the sample:

#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;
}

I'm trying this on Ubuntu 11.04:

$ g++ --version
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2

Anyone knows what I've missed?

解决方案

You have to join std::threads, just like you have to join pthreads.

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

UPDATE: This Debian bug report pointed me to the solution: add -pthread to your commandline. This is most probably a workaround until the std::thread code stabilizes and g++ pulls that library in when it should (or always, for C++).

这篇关于为什么这个简单的std :: thread示例不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆