1 1 #include <future>//进程通信,获取未来的结果 2 2 #include<iostream> 3 3 #include <thread> 4 4 #include <string> 5 5 #include <chrono>//时间 6 6 #include <mutex>//互斥量 7 7 using namespace std; 8 8 9 9 //创建互斥量 1010 mutex m; 1111 1212 //全局通信变量 1313 promise<string> val; 1414 1515 void main() 1616 { 1717 //访问外部变量[=] 1818 auto fun = [=](int index)->int 1919 { 2020 //加锁 2121 lock_guard<mutex> lckg(m); 2222 2323 //显示线程id 2424 cout << "线程编号:" << this_thread::get_id() << " " << index << endl; 2525 //等待十秒 2626 this_thread::sleep_for(chrono::seconds(1)); 2727 2828 //计算 2929 return index * 1024; 3030 }; 3131 3232 //获取返回值,创建任务包 3333 packaged_task<int(int)> pt1(fun); 3434 packaged_task<int(int)> pt2(fun); 3535 3636 thread t1([&]() 3737 { 3838 pt1(23); 3939 }); 4040 thread t2([&]() 4141 { 4242 pt2(26); 4343 }); 4444 4545 //开启线程,获取结果,只能获取一次 4646 int res1 = pt1.get_future().get(); 4747 int res2 = pt2.get_future().get(); 4848 int last = res1 + res2; 4949 cout << last << endl; 5050 5151 t1.joinable(); 5252 t2.joinable(); 5353 t1.join(); 5454 t2.join(); 5555 system("pause"); 5656 }
2.任务包多线程并行计算
Wesley13
2021-10-11
1224 0 0
点赞
收藏
评论区
加载中...