35.并行计算获取结果

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <iostream>
 3 #include <thread> 
 4 #include <future>//线程将来的结果
 5 #include <chrono>
 6 #include <mutex>
 7 using namespace std;
 8 
 9 mutex g_m;
10 
11 
12 void main()
13 {
14     auto run = [=](int index) 
15     {
16         lock_guard<mutex> lckg(g_m);
17         //获取线程id以及参数
18         cout << this_thread::get_id << " " << index << endl;
19         //等待1秒
20         this_thread::sleep_for(chrono::seconds(1));
21         return index * 1024;//返回结果
22     };
23     //创建两任务包,用于初始化线程
24     packaged_task<int(int)> pt1(run);
25     packaged_task<int(int)> pt2(run);
26 
27     //开启线程
28     thread t1([&]() {pt1(2); });
29     thread t2([&]() {pt2(3); });
30     cout << pt1.get_future().get() << endl;
31     cout << pt2.get_future().get() << endl;
32     t1.join();
33     t2.join();
34     cin.get();
35 }

 

转载于:https://www.cnblogs.com/xiaochi/p/8549181.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值