std :: async不并行化任务 [英] std::async doesn't parallelize tasks

查看:135
本文介绍了std :: async不并行化任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码段中使用C ++ 11 std :: async:

Using C++11 std::async in this snippet:

int foo()
{
    ::sleep(2);
    return 123;
}

int main()
{
    future<int> r1(async(foo));
    int r2 = foo();
    cout << r1.get() + r2 << endl;
    return 0;
}

它产生正确的结果,但是同时运行两个foo(整个应用程序运行4秒).编译为: g++ -std=gnu++11 -O2 foo.cc -lpthread(Ubuntu 12.10 64bit,gcc 4.7.2)

It produces the right result, but runs both foo's serially (whole app runs 4 seconds). Compiled as: g++ -std=gnu++11 -O2 foo.cc -lpthread (Ubuntu 12.10 64bit, gcc 4.7.2)

推荐答案

您可能需要添加启动策略std::launch::async:

std::async(std::launch::async, foo);

这篇关于std :: async不并行化任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆