c ++ 11异步seg错误

The*_*Cat 13 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)
Run Code Online (Sandbox Code Playgroud)

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

g++ -std=c++11 c11.cpp
Run Code Online (Sandbox Code Playgroud)

代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

小智 23

我相信这是因为您忘记链接POSIX线程库.只需添加-pthread-lpthreadg++标志和问题应该消失.

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

  • FWIW,单独添加-lpthread不起作用,但-pthread确实如此. (2认同)