c++ async sometimes resulting in std::system_error

2019-08-23 02:21发布

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 ?

0条回答
登录 后发表回答