×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: C++
Posted by: Jeff Bakst
Added: Oct 18, 2017 11:20 PM
Views: 7
Tags: async future
async future examples
  1. #include <cstdlib>
  2. #include <future>
  3. #include <iostream>
  4. #include <thread>
  5.  
  6. using namespace std;
  7.  
  8. std::future<void> task;
  9.  
  10. void doBackgroundTask() {
  11.     std::cout << "doBackgroundTask" << "\n";
  12.     std::this_thread::sleep_for(2s);
  13. }
  14.  
  15. std::future<void> doTask() {
  16.     //task = std::async(std::launch::async, [](){doBackgroundTask();});
  17.     return std::async(std::launch::async, []() {
  18.         doBackgroundTask();
  19.     });
  20. }
  21.  
  22. /*
  23.  *
  24.  */
  25. int main(int argc, char** argv) {
  26.  
  27.     std::cout << "starting task" << "\n";
  28.     std::future<void> t = doTask();
  29.     std::cout << "task started" << "\n";
  30.     t.wait();
  31.     std::cout << "task ended" << "\n";
  32.  
  33.     return 0;
  34. }