1

我正在使用 vc++ 2013 速成版。我正在研究 c++11 的一些新特性,比如 std::async 和 std::future。

我有一个类 Foo,带有一个std::shared_ptr<std::vector<unsigned int> >. 在 Foo ctor 中,我使用 std::make_shared 在堆中分配向量;

来自 Foo.h

Class Foo{
public:
  Foo();
private:
  std::shared_ptr<std::vector<unsigned int> >  testVector;
  unsigned int MAX_ITERATIONS = 800000000;
  void fooFunction();

}

来自 Foo.cpp

Foo::Foo(){
testVector = std::make_shared<std::vector<unsigned int> >();
//fooFunction(); this take about 20 sec
 std::async(std::launch::async, &Foo::fooFunction, this).get(); // and this about the same!!
}


void Foo:fooFunction(){
  for (unsigned int i = 0; i < MAX_ITERATIONS; i++){
    testVector->push_back(i);       
  } 

}

问题是我在调用 std::async(std::launch::async, &Foo::fooFunction, this).get(); 之间看不到任何好处 和 fooFunction();

为什么??任何帮助将不胜感激。此致

4

1 回答 1

2

std::async返回一个std::future

调用get()future 将使它等到结果可用,然后返回它。因此,即使它是异步运行的,您也只能等待结果。

std::async不会神奇地并行forFoo::fooFunction.

于 2014-01-07T15:51:38.583 回答