gpt4 book ai didi

c++ - VS2015 std::async 奇怪

转载 作者:太空狗 更新时间:2023-10-29 20:02:12 27 4
gpt4 key购买 nike

在下面的 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);

}

最佳答案

这与 Visual Studio 无关,但你正在用 std::future 做什么std::async 返回的对象。

std::future 对象被析构时,the destructor在等待 future 准备就绪时阻止

第一行发生的事情是您创建了三个 future 对象,并且在完整表达式的末尾(在您创建最后一个对象之后)futures 超出范围并被销毁。

在“第二次测试”中,您创建了一个 future ,在继续之前必须将其销毁,然后您将创建另一个必须在继续之前销毁的 future ,最后当然也必须销毁第三个 future 。

如果您在临时变量中保存第二个测试中的 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);

关于c++ - VS2015 std::async 奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45073446/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com