hthread.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #ifndef H_THREAD_H
  2. #define H_THREAD_H
  3. #include "hdef.h"
  4. #include "hplatform.h"
  5. #include <thread>
  6. #include <atomic>
  7. #ifdef _MSC_VER
  8. inline uint32 getpid(){
  9. return GetCurrentProcessId();
  10. }
  11. #endif
  12. inline uint32 gettid(){
  13. #ifdef _MSC_VER
  14. return GetCurrentThreadId();
  15. #else
  16. return pthread_self();
  17. #endif
  18. }
  19. /************************************************
  20. * HThread
  21. * Status: STOP,RUNNING,PAUSE
  22. * Control: start,stop,pause,resume
  23. * first-level virtual: doTask
  24. * second-level virtual: run
  25. ************************************************/
  26. class HThread{
  27. public:
  28. HThread() {
  29. status = STOP;
  30. }
  31. virtual ~HThread() {
  32. }
  33. virtual int start() {
  34. if (status == STOP) {
  35. status = RUNNING;
  36. thread = std::thread(&HThread::thread_proc, this);
  37. }
  38. return 0;
  39. }
  40. virtual int stop() {
  41. if (status != STOP) {
  42. status = STOP;
  43. thread.join(); // wait thread exit
  44. }
  45. return 0;
  46. }
  47. virtual int pause() {
  48. if (status == RUNNING) {
  49. status = PAUSE;
  50. }
  51. return 0;
  52. }
  53. virtual int resume() {
  54. if (status == PAUSE) {
  55. status = RUNNING;
  56. }
  57. return 0;
  58. }
  59. void thread_proc() {
  60. doPrepare();
  61. run();
  62. doFinish();
  63. }
  64. virtual void run() {
  65. while (status != STOP) {
  66. while (status == PAUSE) {
  67. std::this_thread::yield();
  68. }
  69. doTask();
  70. std::this_thread::yield();
  71. }
  72. }
  73. virtual void doPrepare() {}
  74. virtual void doTask() {}
  75. virtual void doFinish() {}
  76. std::thread thread;
  77. enum Status {
  78. STOP,
  79. RUNNING,
  80. PAUSE,
  81. };
  82. std::atomic<Status> status;
  83. };
  84. #endif // H_THREAD_H