VS2015 std :: async很奇怪

Rob*_*bin 3 c++ stdasync visual-studio-2015

在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);

}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 8

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

当一个std::future对象被破坏时,析构函数会 在等待未来准备就绪时阻塞.

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

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

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

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);
Run Code Online (Sandbox Code Playgroud)

  • 我认为破坏顺序对你的情况没有影响,关键是所有3个线程在任何等待发生之前启动; 在此之后加入线程的时间或顺序无关紧要.顺便说一句,不能保证看到'ace`作为开始顺序,它很可能但也许一个线程会遇到延迟启动 (4认同)
  • @Rakete1111临时演员在相同的完整表达中以相反的构造顺序被破坏; 除了由于被绑定到参考而延长寿命的那些.(这些没有). (2认同)