hthread.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. dotask_cnt = 0;
  37. thread = std::thread([this]{
  38. doPrepare();
  39. run();
  40. doFinish();
  41. });
  42. }
  43. return 0;
  44. }
  45. virtual int stop() {
  46. if (status != STOP) {
  47. status = STOP;
  48. thread.join(); // wait thread exit
  49. }
  50. return 0;
  51. }
  52. virtual int pause() {
  53. if (status == RUNNING) {
  54. status = PAUSE;
  55. }
  56. return 0;
  57. }
  58. virtual int resume() {
  59. if (status == PAUSE) {
  60. status = RUNNING;
  61. }
  62. return 0;
  63. }
  64. virtual void run() {
  65. while (status != STOP) {
  66. while (status == PAUSE) {
  67. std::this_thread::yield();
  68. }
  69. doTask();
  70. dotask_cnt++;
  71. std::this_thread::yield();
  72. }
  73. }
  74. virtual void doPrepare() {}
  75. virtual void doTask() {}
  76. virtual void doFinish() {}
  77. std::thread thread;
  78. enum Status {
  79. STOP,
  80. RUNNING,
  81. PAUSE,
  82. };
  83. std::atomic<Status> status;
  84. uint32 dotask_cnt;
  85. };
  86. #endif // H_THREAD_H