编程语言
首页 > 编程语言> > C++多线程---packaged_task

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;
//
//}

标签:std,task,cout,int,packaged,---,include,多线程
来源: https://www.cnblogs.com/shuimuqingyang/p/13929848.html