c++ async sometimes resulting in std::system_error , and sometimes not

这一生的挚爱 提交于 2020-01-07 04:51:09

问题


I am trying to get the code example from there to work:

https://solarianprogrammer.com/2012/10/17/cpp-11-async-tutorial/

int twice(int m){
  return 2*m;
}

int main(){

  std::vector< std::future<int> > futures;
  for(int i=0;i<10;++i){
    futures.push_back(std::async(twice,i));
  }

  for(auto &e:futures){
    std::cout << e.get() << std::endl;
  }

  return 0;

}

This code results in:

terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1

I am using these flags for compilation:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread")

The code below results in the same error (we just instantiate some minimal and unused object):

int twice(int m){
  return 2*m;
}

class Foo {
public:
  Foo();
};
Foo::Foo(){}


int main(){

  Foo foo;

  std::vector< std::future<int> > futures;
  for(int i=0;i<10;++i){
    futures.push_back(std::async(twice,i));
  }

  for(auto &e:futures){
    std::cout << e.get() << std::endl;
  }

  return 0;

}

This ends up with the similar results:

terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1

But this works fine (i.e. prints: 0 2 4 ... 18 as expected):

int twice(int m){
  return 2*m;
}

int main(){

  nsp::Foo foo; // <---- difference here !

  std::vector< std::future<int> > futures;
  for(int i=0;i<10;++i){
    futures.push_back(std::async(twice,i));
  }

  for(auto &e:futures){
    std::cout << e.get() << std::endl;
  }

  return 0;

}

nsp::Foo is now defined/declared in another library (but with the same code). This library in compiled in the same CMakeLists.txt folder with the same compilation flags. And the executable links to it.

What is going on ?

来源:https://stackoverflow.com/questions/46634629/c-async-sometimes-resulting-in-stdsystem-error-and-sometimes-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!