C++ promise

#include <iostream>
#include <future>

void mythread(std::promise<int> &promise, int arg)
{
   std::cout << "mythread " << std::this_thread::get_id() << std::endl;
   std::cout << "arg " << arg << std::endl;
   arg += 5;
   promise.set_value(arg);

   std::chrono::milliseconds second(3000);
   std::this_thread::sleep_for(second);
}

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

   std::promise<int> promise;
   std::thread t(mythread, std::ref(promise), 10);
   t.join();
   std::cout << "join" << std::endl;

   std::future<int> ret = promise.get_future();
   std::cout << "future " << ret.get() << std::endl;

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

   return 0;
}
$ g++ promise.cpp -std=c++11 -pthread
$ ./a.out 
main 139680372819776
mythread 139680355481344
arg 10
join
future 15
end
posted @ 2022-08-08 16:25  thomas_blog  阅读(274)  评论(0)    收藏  举报