BusyThread.cpp
上传用户:dzyhzl
上传日期:2019-04-29
资源大小:56270k
文件大小:2k
源码类别:

模拟服务器

开发平台:

C/C++

  1. // BusyThread.cpp: implementation of the CBusyThread class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "StdAfx.h"
  5. #include "BusyThread.h"
  6. //////////////////////////////////////////////////////////////////////
  7. // Construction/Destruction
  8. //////////////////////////////////////////////////////////////////////
  9. CBusyThread::CBusyThread()
  10. {
  11. m_hStop = NULL;
  12. m_hProcessor = NULL;
  13. }
  14. CBusyThread::~CBusyThread()
  15. {
  16. ASSERT(m_hStop == NULL);
  17. ASSERT(m_hProcessor == NULL);
  18. }
  19. int CBusyThread::IsThreadOK()
  20. {
  21.     return (m_hProcessor != NULL);
  22. }
  23. int CBusyThread::StartThread()
  24. {
  25. int nRet = 0;
  26. if ( NULL != m_hProcessor ) // The thread has been running.
  27. {
  28. return nRet;
  29. }
  30. if (NULL == m_hStop)
  31. {
  32. m_hStop = CreateEvent(NULL, TRUE, FALSE, NULL);
  33. }
  34. DWORD dwThreadID = 0;
  35. m_hProcessor = CreateThread(NULL, 0, CBusyThread::InnerThreadProc, (LPVOID)this, 0, &dwThreadID);
  36. nRet = m_hProcessor != NULL;
  37. return nRet;
  38. }
  39. int CBusyThread::StopThread()
  40. {
  41. int bRet = FALSE;
  42. if (NULL == m_hProcessor
  43. || NULL == m_hStop)
  44. {
  45. bRet = TRUE;
  46. return bRet;
  47. }
  48. SetEvent(m_hStop);
  49. DWORD dwResult = WaitForSingleObject(m_hProcessor, INFINITE);
  50. if (WAIT_FAILED == dwResult)
  51. {
  52. bRet = FALSE;
  53. }
  54. else if (WAIT_OBJECT_0 == dwResult)
  55. {
  56. bRet = TRUE;
  57. }
  58. else if (WAIT_TIMEOUT == dwResult) // Time out.
  59. {
  60. if (TerminateThread(m_hProcessor, 0))
  61. {
  62. bRet = TRUE;
  63. }
  64. else
  65. {
  66. bRet = FALSE;
  67. }
  68. }
  69. if (bRet)
  70. {
  71. CloseHandle(m_hStop);
  72. m_hStop = NULL;
  73. CloseHandle(m_hProcessor);
  74. m_hProcessor = NULL;
  75. }
  76. return bRet;
  77. }
  78. int CBusyThread::PreExecution()
  79. {
  80.     return true;
  81. }
  82. void CBusyThread::PostExecution()
  83. {
  84. }
  85. DWORD WINAPI CBusyThread::InnerThreadProc(LPVOID lpThisParam)
  86. {
  87.     ULONG ulResult = -1;
  88.     
  89.     int nRetCode = false;
  90.     CBusyThread *pThis = (CBusyThread *)lpThisParam;
  91.     
  92.     ASSERT_POINTER(pThis, CBusyThread);
  93.     
  94.     if (NULL == pThis)
  95.         goto Exit0;
  96.     
  97.     nRetCode = pThis->PreExecution();
  98.     if (!nRetCode)
  99.         goto Exit0;
  100.     
  101.     ulResult = pThis->MainExecution();
  102.     pThis->PostExecution();
  103.     
  104. Exit0:
  105.     return ulResult;
  106. }