Clone of UAS2 @ https://github.com/drudgedance/uas2

Timer.cpp 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Timer.cpp: implementation of the Timer class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "Timer.h"
  6. #ifdef _DEBUG
  7. #undef THIS_FILE
  8. static char THIS_FILE[]=__FILE__;
  9. #define new DEBUG_NEW
  10. #endif
  11. //////////////////////////////////////////////////////////////////////
  12. // Construction/Destruction
  13. //////////////////////////////////////////////////////////////////////
  14. Timer::Timer()
  15. {
  16. m_bStop=true;
  17. m_msTimeout=-1;
  18. m_hThreadDone = NULL;
  19. m_hThreadDone = CreateEvent(NULL,FALSE, FALSE, NULL);
  20. ASSERT (m_hThreadDone);
  21. SetEvent(m_hThreadDone);
  22. // code added
  23. m_hEndThread = NULL;
  24. m_hEndThread = CreateEvent(NULL,FALSE, FALSE, NULL);
  25. ASSERT (m_hEndThread);
  26. SetEvent(m_hEndThread);
  27. }
  28. Timer::~Timer()
  29. {
  30. //dont destruct until the thread is done
  31. DWORD ret=WaitForSingleObject(m_hEndThread,INFINITE);
  32. ASSERT(ret==WAIT_OBJECT_0);
  33. Sleep(500);
  34. CloseHandle(m_hEndThread) ;
  35. }
  36. void Timer::Tick()
  37. {
  38. //Will be overriden by subclass
  39. }
  40. void Timer::StartTicking()
  41. {
  42. if (m_bStop==false)
  43. return; ///ignore, it is already ticking...
  44. m_bStop=false;
  45. ResetEvent(m_hThreadDone);
  46. ResetEvent(m_hEndThread);
  47. AfxBeginThread(TickerThread, this);
  48. }
  49. UINT Timer::TickerThread(LPVOID pParam)
  50. {
  51. Timer* me=(Timer*) pParam;
  52. ASSERT (me->m_msTimeout!=-1);
  53. while (!me->m_bStop)
  54. {
  55. // Sleep() is changed to this so that a termination of a thread will be received.
  56. if (WaitForSingleObject(me->m_hEndThread,me->GetTimeout()) == WAIT_TIMEOUT)
  57. {
  58. // No signal received..
  59. me->Tick();
  60. }
  61. else
  62. {
  63. // Signal received to stop the thread.
  64. me->m_bStop = true;
  65. }
  66. }
  67. SetEvent(me->m_hThreadDone);
  68. return 0;
  69. }
  70. void Timer::StopTicking()
  71. {
  72. if (m_bStop==true)
  73. return; ///ignore, it is not ticking...
  74. m_bStop=true; //ok make it stop
  75. SetEvent(m_hEndThread);
  76. WaitForSingleObject(m_hThreadDone,INFINITE);
  77. //The above ensures that we do not return UNTIL the thread
  78. //has finished. This way we dont allow the user to start multiple
  79. //threads that will execute Tick() at the same time
  80. }