c++线程、定时器的使用

封装成了一个类,以便很好的进行参数传递使用。

TimerThread.h


   
   
   
   
  1. #pragma once
  2. #ifndef APLAYER_TIMERTHREAD_H
  3. #define APLAYER_TIMERTHREAD_H
  4. #include
  5. #include
  6. class cTimerThread {
  7. public:
  8. cTimerThread()
  9. {
  10. }
  11. ~cTimerThread()
  12. {
  13. // KillTimer();
  14. }
  15. int CreateTimer(unsigned int interval, PTIMERAPCROUTINE func, void* lpParam);
  16. // void KillTimer();
  17. public:
  18. std:: string name;
  19. std:: string job_id;
  20. bool _bRunning;
  21. private:
  22. static DWORD WINAPI timerThread(LPVOID lpParam);
  23. HANDLE _hTimer;
  24. int _nInterval;
  25. HANDLE _hEvent;
  26. void* _lpParam;
  27. PTIMERAPCROUTINE _callbackFunc;
  28. HANDLE _hThread;
  29. DWORD _dwThread;
  30. };
  31. #endif

TimerThread.cpp


   
   
   
   
  1. #include
  2. #include
  3. #include "TimerThread.h"
  4. #include
  5. using namespace std;
  6. int a = 0;
  7. VOID APIENTRY TimerAPCRoutine(PVOID pvArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
  8. {
  9. a++;
  10. cTimerThread* ctt = (cTimerThread* )pvArgToCompletionRoutine;
  11. if (a== 4)
  12. {
  13. ctt->_bRunning = false;
  14. }
  15. std:: cout << a<< "dio:"<< ctt->name.c_str() << std:: endl;
  16. }
  17. int main()
  18. {
  19. string li = "name";
  20. string job_id = "w5";
  21. cTimerThread timer_;
  22. timer_.job_id = job_id;
  23. timer_.name = li;
  24. void *lpParam = NULL;
  25. timer_.CreateTimer( 1000, TimerAPCRoutine, lpParam);
  26. return 0;
  27. }
  28. int cTimerThread::CreateTimer( unsigned int interval, PTIMERAPCROUTINE func, void* lpParam)
  29. {
  30. _nInterval = interval;
  31. _callbackFunc = func;
  32. _lpParam = lpParam;
  33. _bRunning = true;
  34. std:: thread t1(timerThread,this);
  35. t1.join(); //线程执行完自动退出
  36. return 0;
  37. }
  38. DWORD WINAPI cTimerThread::timerThread(LPVOID lpParam) {
  39. cTimerThread* pThis = (cTimerThread*)lpParam;
  40. HANDLE hTimer = CreateWaitableTimer( NULL, FALSE, NULL);
  41. LARGE_INTEGER li;
  42. li.QuadPart = 0;
  43. if (!SetWaitableTimer(hTimer, &li, pThis->_nInterval, pThis->_callbackFunc, pThis, FALSE))
  44. {
  45. CloseHandle(hTimer);
  46. return 0;
  47. }
  48. do
  49. {
  50. SleepEx(pThis->_nInterval, TRUE);
  51. } while (pThis->_bRunning);
  52. CloseHandle(hTimer);
  53. return 0;
  54. }

 

你可能感兴趣的:(C++)