waitable_event.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include<__vic/waitable_event.h>
  2. #include<__vic/thread.h>
  3. #include<iostream>
  4. #include<exception>
  5. #include<cstring>
  6. namespace tests {
  7. //////////////////////////////////////////////////////////////////////////////
  8. class worker_thread : public __vic::thread
  9. {
  10. __vic::waitable_event stop_work;
  11. void worker();
  12. public:
  13. void stop() { stop_work.set(); }
  14. };
  15. //////////////////////////////////////////////////////////////////////////////
  16. //----------------------------------------------------------------------------
  17. bool have_job()
  18. {
  19. static int counter = 0;
  20. if(counter++ > 10)
  21. {
  22. counter = 0;
  23. return false;
  24. }
  25. return true;
  26. }
  27. //----------------------------------------------------------------------------
  28. void process_one_item()
  29. {
  30. __vic::this_thread::sleep_ms(200);
  31. }
  32. //----------------------------------------------------------------------------
  33. void worker_thread::worker()
  34. {
  35. while(!stop_work.signaled())
  36. {
  37. while(have_job())
  38. {
  39. process_one_item();
  40. if(stop_work.signaled()) return;
  41. }
  42. stop_work.wait_ms(1000);
  43. }
  44. }
  45. //----------------------------------------------------------------------------
  46. void run()
  47. {
  48. worker_thread thr;
  49. thr.start();
  50. std::cout << "*** PRESS ENTER TO TERMINATE THREAD ***" << std::endl;
  51. std::cin.get();
  52. thr.stop();
  53. thr.join();
  54. std::cout << "Done" << std::endl;
  55. }
  56. //----------------------------------------------------------------------------
  57. } // namespace
  58. int main(int argc, char *argv[])
  59. {
  60. try
  61. {
  62. if(argc == 2 && std::strcmp(argv[1], "interactive") == 0)
  63. tests::run();
  64. return 0;
  65. }
  66. catch(const std::exception &ex)
  67. {
  68. std::cerr << ex.what() << '\n';
  69. }
  70. return 1;
  71. }