编程语言
首页 > 编程语言> > C++异步async

C++异步async

作者:互联网

#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;

   /*
      async会创建新线程
      deferred不会创建新线程
   */
   std::future<int> ret = std::async(std::launch::async, mythread);

   std::cout << "async" << std::endl;

   /* 卡到这里等待线程结束 */
   std::cout << "future " << ret.get() << std::endl;

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

   return 0;
}
$ ./a.out 
main 140585868318528
async
mythread 140585850980096
future 5
end

标签:std,异步,main,cout,C++,mythread,async,include
来源: https://www.cnblogs.com/zhangxuechao/p/16561889.html