C++包装对象packaged_task

#include <iostream>
#include <future>

int mythread(int arg)
{
   std::cout << "mythread " << std::this_thread::get_id() << std::endl;
   std::cout << "arg " << arg << std::endl;
   std::chrono::milliseconds second(3000);
   std::this_thread::sleep_for(second);
   return 5;
}

int main()
{
   std::cout << "main " << std::this_thread::get_id() << std::endl;

   std::packaged_task<int(int)> pt(mythread); //把mythread通过packaged包装起来 
   std::thread t(std::ref(pt), 10); //线程直接开始运行
   t.join();
   std::cout << "join" << std::endl;
   std::future<int> ret = pt.get_future();
   std::cout << "future " << ret.get() << std::endl;
   std::cout << "end" << std::endl;

   return 0;
}
$ g++ packaged.cpp -std=c++11 -pthread
$ ./a.out                            
main 139877977814848
mythread 139877960476416
arg 10
join
future 5
end
posted @ 2022-08-08 15:41  thomas_blog  阅读(36)  评论(0编辑  收藏  举报