packaged_task & future & async

本文探讨了如何使用packaged_task和async/await实现高效计算,通过将大任务拆分为多个子任务并发执行,展示了doublecomp2和comp4函数中任务拆分与结果合并的方法,适用于大数据处理场景。
摘要由CSDN通过智能技术生成

packaged_task:

double accum(double∗ beg, double ∗ end, double init)
// compute the sum of [beg:end) starting with the initial value init
{
return accumulate(beg,end,init);
}
double comp2(vector<double>& v)
{
using Task_type = double(double∗,double∗,double);
// type of task
packaged_task<Task_type> pt0 {accum};
packaged_task<Task_type> pt1 {accum}; // package the task (i.e., accum)
future<double> f0 {pt0.get_future()};
future<double> f1 {pt1.get_future()}; // get hold of pt0’s future
// get hold of pt1’s future
double∗ first = &v[0];
thread t1 {move(pt0),first,first+v.siz e()/2,0};
thread t2 {move(pt1),first+v.siz e()/2,first+v.siz e(),0}; // star t a thread for pt0
// star t a thread for pt1
// ...
return f0.get()+f1.g et();
// get the results
}

async:

double comp4(vector<double>& v)
// spawn many tasks if v is large enough
{
if (v.siz e()<10000) return accum(v.begin(),v.end(),0.0);
auto v0 = &v[0];
auto sz = v.size();
auto f0 = async(accum,v0,v0+sz/4,0.0);// first quarter
auto f1 = async(accum,v0+sz/4,v0+sz/2,0.0);// second quarter
auto f2 = async(accum,v0+sz/2,v0+sz∗3/4,0.0);// third quarter
auto f3 = async(accum,v0+sz∗3/4,v0+sz,0.0);// four th quar ter

return f0.get()+f1.g et()+f2.get()+f3.get(); // collect and combine the results
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值