c ++ 11异步seg错误

时间:2012-10-18 20:02:28

标签: c++ multithreading asynchronous c++11

我只是尝试使用GCC 4.7.2的一些新的C ++ 11功能,但是当我去运行seg故障时。

$ ./a.out
Message from main.
terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1
Aborted (core dumped)

我使用GCC的'beta'功能编译,关于c ++ 0x:

g++ -std=c++11 c11.cpp

代码:

#include <future>
#include <iostream>

void called_from_async() {
  std::cout << "Async call" << std::endl;
}

int main() {
  //called_from_async launched in a separate thread if possible
  std::future<void> result( std::async(called_from_async));

  std::cout << "Message from main." << std::endl;

  //ensure that called_from_async is launched synchronously 
  //if it wasn't already launched
  result.get();

  return 0;
}

1 个答案:

答案 0 :(得分:23)

我相信这是因为您忘记了与POSIX线程库的链​​接。只需将-pthread-lpthread添加到g++标记中,问题就会消失。

如果您对详细信息感兴趣,则会发生这种情况,因为C ++ 11运行时仅在您碰巧使用这些功能时才在运行时解析来自pthread的符号。因此,如果您忘记链接,运行时将无法解析这些符号,将您的环境视为不支持线程,并抛出异常(您没有捕获它并且它会中止您的应用程序)。

相关问题