C++ wait_for

2022/8/9 1:22:49

本文主要是介绍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


这篇关于C++ wait_for的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程