13

我只是在 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)

关于 c++0x,我使用 GCC 的“测试版”功能进行了编译:

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

1 回答 1

23

我相信发生这种情况是因为您忘记了与 POSIX 线程库链接。只需将-pthread或添加-lpthreadg++标志中,问题就会消失。

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

于 2012-10-18T20:09:37.503 回答