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 << ' ';
//
//        std::this_thread::sleep_for(std::chrono::seconds(1));
//
//    }
//
//    std::cout << "Lift off! ";
//
//    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. ";
//    th.join();
//
//    std::system("pause");
//    return 0;
//
//}
原文地址:https://www.cnblogs.com/shuimuqingyang/p/13929848.html