C 11异步SEG故障

c++11 Async seg fault

本文关键字:故障 SEG 异步      更新时间:2023-10-16

我只是尝试使用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,with:

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

我相信这会发生这种情况,因为您忘记了与Posix Threads库链接。只需将-pthread-lpthread添加到g++标志,问题就应该消失。

如果您对详细信息感兴趣,则会发生这种情况,因为C 11运行时仅在使用这些功能的情况下才能在运行时解决pthread的符号。因此,如果您忘了链接,运行时将无法解决这些符号,将您的环境视为不支持线程并抛出异常(您不会捕获,并且它逐渐删除了您的申请)。