SingleTimer.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "SingleTimer.h"
  2. UINT WINAPI TimerWaitThread(LPVOID pM);
  3. HANDLE hWaitEvent = NULL;
  4. SingleTimer::SingleTimer()
  5. {
  6. m_isRunning = false;
  7. hWaitEvent = CreateEventA(NULL, TRUE, FALSE, 0); //手动设置,初始状态为无信号
  8. m_hWaitThread = NULL;
  9. m_waitMS = 3000;
  10. }
  11. SingleTimer:: ~SingleTimer()
  12. {
  13. if (hWaitEvent)
  14. {
  15. CloseHandle(hWaitEvent);
  16. hWaitEvent = NULL;
  17. }
  18. if (m_hWaitThread)
  19. {
  20. WaitForSingleObject(m_hWaitThread, INFINITE); //等待线程执行完
  21. CloseHandle(m_hWaitThread);
  22. m_hWaitThread = NULL;
  23. }
  24. }
  25. void SingleTimer::start()
  26. {
  27. if(isRunning())
  28. return;
  29. m_isRunning = TRUE;
  30. m_hWaitThread = (HANDLE)_beginthreadex(NULL, 0, TimerWaitThread, this, 0, NULL);
  31. }
  32. void SingleTimer::stop()
  33. {
  34. m_isRunning = FALSE;
  35. }
  36. bool SingleTimer::isRunning() const
  37. {
  38. return m_isRunning;
  39. }
  40. void SingleTimer::setWaitTime(int wTime)
  41. {
  42. m_waitMS = wTime;
  43. }
  44. int SingleTimer::waitTime() const
  45. {
  46. return m_waitMS;
  47. }
  48. //等待线程
  49. UINT WINAPI TimerWaitThread(LPVOID pM)
  50. {
  51. SingleTimer *timer = (SingleTimer*)pM;
  52. DWORD dwRet = WaitForSingleObject(hWaitEvent, timer->waitTime()); //挂起线程
  53. timer->stop();
  54. return 0;
  55. }