fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <chrono>
  4. #include <thread>
  5. #include <atomic>
  6. #include <mutex>
  7.  
  8. std::mutex mutex;
  9. std::atomic<bool> stop = {false};
  10. unsigned last_result = 0; // Whatever thread_1ms produces.
  11.  
  12. void thread_1ms_action() {
  13. // Do the work.
  14.  
  15. // Update the last result.
  16. {
  17. std::unique_lock<std::mutex> lock(mutex);
  18. ++last_result;
  19. }
  20. }
  21.  
  22. void thread_1333us_action() {
  23. // Copy thread_1ms result.
  24. unsigned last_result_copy;
  25. {
  26. std::unique_lock<std::mutex> lock(mutex);
  27. last_result_copy = last_result;
  28. }
  29.  
  30. // Do the work.
  31. std::cout << last_result_copy << '\n';
  32. }
  33.  
  34. void periodic_action_thread(std::chrono::microseconds period, std::function<void()> const& action) {
  35. auto const start = std::chrono::steady_clock::now();
  36. while(!stop.load(std::memory_order_relaxed)) {
  37. // Do the work.
  38. action();
  39.  
  40. // Wait till the next period start.
  41. auto now = std::chrono::steady_clock::now();
  42. auto iterations = (now - start) / period;
  43. auto next_start = start + (iterations + 1) * period;
  44. std::this_thread::sleep_until(next_start);
  45. }
  46. }
  47.  
  48. int main() {
  49. std::thread a(periodic_action_thread, std::chrono::milliseconds(1), thread_1ms_action);
  50. std::thread b(periodic_action_thread, std::chrono::microseconds(13333), thread_1333us_action);
  51.  
  52. std::this_thread::sleep_for(std::chrono::seconds(1));
  53. stop = true;
  54. a.join();
  55. b.join();
  56. }
  57.  
Success #stdin #stdout 0s 84864KB
stdin
Standard input is empty
stdout
0
14
27
40
54
67
80
94
107
120
134
147
160
174
187
200
214
227
240
254
267
280
294
307
320
334
347
360
374
387
400
414
427
440
454
467
480
494
507
520
534
547
560
574
587
600
614
627
640
654
667
680
694
707
720
734
747
760
774
787
800
814
827
840
854
867
880
894
907
920
934
947
960
974
987
1000