900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 2.任务包多线程并行计算

2.任务包多线程并行计算

时间:2024-05-02 07:44:30

相关推荐

2.任务包多线程并行计算

1 #include <future>//进程通信,获取未来的结果 2 #include<iostream> 3 #include <thread> 4 #include <string> 5 #include <chrono>//时间 6 #include <mutex>//互斥量 7 using namespace std; 8 9 //创建互斥量10 mutex m;11 12 //全局通信变量13 promise<string> val;14 15 void main()16 {17//访问外部变量[=]18auto fun = [=](int index)->int19{20 //加锁21 lock_guard<mutex> lckg(m);22 23 //显示线程id24 cout << "线程编号:" << this_thread::get_id() << " " << index << endl;25 //等待十秒26 this_thread::sleep_for(chrono::seconds(1));27 28 //计算29 return index * 1024;30};31 32//获取返回值,创建任务包33packaged_task<int(int)> pt1(fun);34packaged_task<int(int)> pt2(fun);35 36thread t1([&]() 37{38 pt1(23); 39});40thread t2([&]()41{42 pt2(26);43});44 45//开启线程,获取结果,只能获取一次46int res1 = pt1.get_future().get();47int res2 = pt2.get_future().get();48int last = res1 + res2;49cout << last << endl;50 51t1.joinable();52t2.joinable();53t1.join();54t2.join();55system("pause");56 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。