fork download
  1. #include <thread>
  2. #include <iostream>
  3. #include <assert.h>
  4. #include <chrono>
  5. #include <future>
  6. void threadFunction(std::future<void> futureObj)
  7. {
  8. std::cout << "Thread Start" << std::endl;
  9. while (futureObj.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout)
  10. {
  11. std::cout << "Doing Some Work" << std::endl;
  12. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  13. }
  14. std::cout << "Thread End" << std::endl;
  15. }
  16. int main()
  17. {
  18. using namespace std::chrono_literals;
  19. // Create a std::promise object
  20. std::promise<void> exitSignal;
  21. //Fetch std::future object associated with promise
  22. std::future<void> futureObj = exitSignal.get_future();
  23. // Starting Thread & move the future object in lambda function by reference
  24. std::thread th(&threadFunction, std::move(futureObj));
  25. //Wait for 10 sec
  26.  
  27. auto start = std::chrono::high_resolution_clock::now();
  28. std::this_thread::sleep_for(10000ms);
  29. auto end = std::chrono::high_resolution_clock::now();
  30. std::chrono::duration<double, std::milli> elapsed = end-start;
  31. std::cout << "Waited " << elapsed.count() << " ms\n";
  32.  
  33. std::cout << "Asking Thread to Stop" << std::endl;
  34. //Set the value in promise
  35. exitSignal.set_value();
  36. //Wait for thread to join
  37. th.join();
  38. std::cout << "Exiting Main Function" << std::endl;
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5532KB
stdin
Standard input is empty
stdout
Thread Start
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Doing Some Work
Waited 10000.1 ms
Asking Thread to Stop
Thread End
Exiting Main Function