thread.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #ifndef __THREAD_H__
  2. #define __THREAD_H__
  3. #include <string>
  4. #include <windows.h>
  5. #include <process.h>
  6. class Runnable
  7. {
  8. public:
  9. virtual ~Runnable() {};
  10. virtual void Run() = 0;
  11. virtual void Init(){};
  12. };
  13. class CThread : public Runnable
  14. {
  15. private:
  16. explicit CThread(const CThread & rhs);
  17. public:
  18. CThread();
  19. CThread(Runnable * pRunnable);
  20. CThread(const char * ThreadName, Runnable * pRunnable = NULL);
  21. CThread(std::string ThreadName, Runnable * pRunnable = NULL);
  22. ~CThread(void);
  23. /**
  24. 开始运行线程
  25. @arg bSuspend 开始运行时是否挂起
  26. **/
  27. bool Start(bool bSuspend = false);
  28. /**
  29. 运行的线程函数,可以使用派生类重写此函数
  30. **/
  31. virtual void Run();
  32. /**
  33. 当前执行此函数线程等待线程结束
  34. @arg timeout 等待超时时间,如果为负数,等待无限时长
  35. **/
  36. void Join(int timeout = -1);
  37. /**
  38. 恢复挂起的线程
  39. **/
  40. void Resume();
  41. /**
  42. 挂起线程
  43. **/
  44. void Suspend();
  45. /**
  46. 终止线程的执行
  47. **/
  48. bool Terminate(unsigned long ExitCode);
  49. unsigned int GetThreadID();
  50. std::string GetThreadName();
  51. void SetThreadName(std::string ThreadName);
  52. void SetThreadName(const char * ThreadName);
  53. private:
  54. static unsigned int WINAPI StaticThreadFunc(void * arg);
  55. private:
  56. HANDLE m_handle;
  57. Runnable * const m_pRunnable;
  58. unsigned int m_ThreadID;
  59. std::string m_ThreadName;
  60. volatile bool m_bRun;
  61. };
  62. #endif