VS2015 std :: async很奇怪

时间:2017-07-13 06:56:44

标签: c++ visual-studio-2015 stdasync

在VS2015的以下代码中,我在第一行收到acefbd,这是正确的。但在第二次测试中,我分成单独的行,输出为abcdef

这是预期的行为吗?

#include <future>
#include <iostream>

using namespace std;

void a () {
std::cout << "a";
std::this_thread::sleep_for (std::chrono::seconds (3));
std::cout << "b";
}

void c () {
std::cout << "c";
std::this_thread::sleep_for (std::chrono::seconds (4));
std::cout << "d";
}

void e () {
std::cout << "e";
std::this_thread::sleep_for (std::chrono::seconds (2));
std::cout << "f";
}

int main () 
{
    std::async (std::launch::async, a), std::async (std::launch::async, c),  std::async (std::launch::async, e);

cout << "\n2nd Test" << endl;

std::async (std::launch::async, a);
std::async (std::launch::async, c);
std::async (std::launch::async, e);

}

1 个答案:

答案 0 :(得分:8)

这与Visual Studio无关,而是与std::async返回的std::future个对象有关。

std::future对象被破坏时,the destructor 阻止,等待将来准备就绪。

第一行的结果是你创建了三个未来的对象,并且在完整表达式的末尾(在你创建最后一个对象之后),期货超出范围并被破坏。

在&#34;第二次测试&#34;你创造了一个在继续之前必须被破坏的未来,然后你创造了另一个在继续之前必须被破坏的未来,最后是第三个未来,当然也必须被破坏。

如果你在临时变量的第二次测试中保存期货,你应该得到同样的行为:

auto temp_a = std::async (std::launch::async, a);
auto temp_c = std::async (std::launch::async, c);
auto temp_e = std::async (std::launch::async, e);