C++多线程---packaged_task

#include<iostream>
#include<string>
#include<thread>
#include<mutex>
#include<fstream>
#include<future>
#include<deque>
#include<mutex>
int faactorial(int N) {
 int res = -1;
 for (int i = N; i > 1; i--) {
  res += i;
 }
 std::cout << "result is" << res << std::endl;
 return res;
}
std::deque<std::packaged_task<int()>> task_q;
std::mutex mu;
std::condition_variable cond;
void thread_1()
{
 std::packaged_task<int()> t;
 {
  std::unique_lock<std::mutex> locker(mu);
  cond.wait(locker, [] {return !task_q.empty(); });
  t = std::move(task_q.front());//将主线程中获取到的t move出来并调用它
 }
 
 t();//调用并执行t
 //std::cout << "t()" << t() << std::endl;
 
}
 
int main() {
 //使用线程
 std::thread t1(thread_1);
 //使用package 可以异步获取结果
 std::packaged_task<int()> t(std::bind(faactorial,6));
 std::future<int> ret = t.get_future();//获得与packaged_task共享状态相关联的future对象
 {
  std::unique_lock<std::mutex> locker(mu);
  task_q.push_back(std::move(t));//主线程创建一个packaged_task对象并将其push到队列中
 
 }
 cond.notify_one();
   
 int value = ret.get(); // 等待任务并获取结果
 std::cout << "value: " << value << std::endl;
 t1.join();
 std::system("pause");

}
 
//#include <iostream>     // std::cout
//#include <future>       // std::packaged_task, std::future
//#include <chrono>       // std::chrono::seconds
//#include <thread>       // std::thread, std::this_thread::sleep_for
//
//
//int countdown(int from, int to) {
//
//    for (int i = from; i != to; --i) {
//
//        std::cout << i << '\n';
//
//        std::this_thread::sleep_for(std::chrono::seconds(1));
//
//    }
//
//    std::cout << "Lift off!\n";
//
//    return from - to;
//
//}
//
//
//
//int main()
//
//{
//    std::packaged_task<int(int, int)> tsk(countdown);   // set up packaged_task
//    std::future<int> ret = tsk.get_future();            // get future
//    std::thread th(std::move(tsk), 10, 0);   // spawn thread to count down from 10 to 0
//  
//    for (int i = 0; i < 10; i++) {
//        std::cout << "main" << std::endl;
//    }
//    int value = ret.get();                  // wait for the task to finish and get result
//    std::cout << "The countdown lasted for " << value << " seconds.\n";
//    th.join();
//
//    std::system("pause");
//    return 0;
//
//}
posted @   水木清扬  阅读(330)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示