【问题标题】:Speeding up std:.vector filling with new c++11 std::async使用新的 c++11 std::async 加速 std:.vector 填充
【发布时间】:2014-01-07 23:51:38
【问题描述】:

我使用的是 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();

为什么? 任何帮助将不胜感激。 最好的问候

【问题讨论】:

  • 您为什么认为时间会有所不同?无论如何,您的代码都被有效地序列化了。

标签: c++11 vector stdasync


【解决方案1】:

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

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

std::async 不会神奇地并行化 Foo::fooFunction 中的 for 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多