c – VS2015 std :: async很奇怪

c – VS2015 std :: async很奇怪,第1张

概述在VS2015的下面代码中,我在第一行获得了acefbd,这是正确的.但在第二次测试中,我分成单独的行,输出是abcdef. 这是预期的行为吗? #include <future>#include <iostream>using namespace std;void a () {std::cout << "a";std::this_thread::sleep_for (std::ch 在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),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 :: async返回的 std::future对象有关.

当std :: future对象被破坏时,the destructor会在等待未来准备就绪时阻塞.

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

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

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

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很奇怪全部内容,希望文章能够帮你解决c – VS2015 std :: async很奇怪所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1217764.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存