Thread.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Thread.h
  3. *
  4. * Created on: Aug 24, 2017
  5. * Author: guoxs
  6. */
  7. #ifndef _SYSTEM_THREAD_H_
  8. #define _SYSTEM_THREAD_H_
  9. #include "Mutex.h"
  10. #include "Condition.h"
  11. /**
  12. * @brief 线程类
  13. */
  14. class Thread {
  15. public:
  16. Thread();
  17. virtual ~Thread();
  18. /**
  19. * @brief 启动线程
  20. * @param name 线程名称;默认为NULL,由系统自动分配
  21. */
  22. bool run(const char *name = 0);
  23. /**
  24. * @brief 请求退出线程
  25. * @attention 调用完函数立即返回,并不代表线程也退出了
  26. */
  27. void requestExit();
  28. /**
  29. * @brief 请求并等待线程退出
  30. * @attention 线程退出,函数才返回
  31. */
  32. void requestExitAndWait();
  33. /**
  34. * @brief 线程是否运行中
  35. */
  36. bool isRunning() const;
  37. static void sleep(int msec);
  38. protected:
  39. /**
  40. * @brief 是否有退出线程请求
  41. */
  42. bool exitPending() const;
  43. /**
  44. * @brief 线程开始运行时回调该接口
  45. */
  46. virtual bool readyToRun();
  47. /**
  48. * @brief 线程循环调用该接口
  49. * @return true 不退出线程,false 将退出线程
  50. */
  51. virtual bool threadLoop() = 0;
  52. private:
  53. Thread& operator=(const Thread&);
  54. static void* _threadLoop(void *user);
  55. private:
  56. typedef struct {
  57. void *userData;
  58. char *threadName;
  59. } SThreadData;
  60. bool mExitPending;
  61. bool mIsRunning;
  62. Condition mThreadExitedCondition;
  63. mutable Mutex mLock;
  64. };
  65. #endif /* _SYSTEM_THREAD_H_ */