C++ wait_for

#include <iostream>
#include <future>

int mythread()
{
   std::cout << "mythread " << std::this_thread::get_id() << 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::future<int> ret = std::async(std::launch::async, mythread);

   std::future_status status = ret.wait_for(std::chrono::seconds(2));
   switch(status)
   {
      case std::future_status::timeout:
         std::cout << "timeout" << std::endl;
      break;
      case std::future_status::ready:
         std::cout << "ready" << std::endl;
      break;
      case std::future_status::deferred:
         std::cout << "deferred" << std::endl;
      break;
      default:
      break;
   }

   std::cout << "future " << ret.get() << std::endl;

   std::cout << "end" << std::endl;

   return 0;
}
$ g++ wait_for.cpp -std=c++11 -pthread
$ ./a.out 
main 140534331926336
mythread 140534314587904
timeout
future 5
end
std::future_status status = ret.wait_for(std::chrono::seconds(4));  
$ ./a.out                             
main 140365530023744
mythread 140365512685312
ready
future 5
end
std::future<int> ret = std::async(std::launch::deferred, mythread);
$ ./a.out 
main 140412357789504
deferred
mythread 140412357789504
future 5
end
posted @   thomas_blog  阅读(656)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示