1
0

htask.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #ifndef H_TASK_H_
  2. #define H_TASK_H_
  3. #include <mutex>
  4. #include <condition_variable>
  5. #include "hobj.h"
  6. #include "herr.h"
  7. #define DEFAULT_TASK_TIMEOUT 5000 // ms
  8. class HTask : public HObj {
  9. public:
  10. enum State {
  11. TASK_STATE_NOT_READY,
  12. TASK_STATE_READY,
  13. TASK_STATE_EXECUTING,
  14. TASK_STATE_FINISHED,
  15. TASK_STATE_ERROR
  16. };
  17. HTask() {
  18. state_ = TASK_STATE_NOT_READY;
  19. errno_ = 0;
  20. is_wait_ = false;
  21. timeout_ = DEFAULT_TASK_TIMEOUT;
  22. }
  23. ~HTask() {
  24. }
  25. State GetState() {return state_;}
  26. int GetErrno() {return errno_;}
  27. void SetErrno(int errcode) {
  28. errno_ = errcode;
  29. if (errno_ != 0) {
  30. state_ = TASK_STATE_ERROR;
  31. }
  32. }
  33. virtual int Ready() {
  34. state_ = TASK_STATE_READY;
  35. return 0;
  36. }
  37. virtual int Exec() {
  38. state_ = TASK_STATE_EXECUTING;
  39. return 0;
  40. }
  41. virtual int Finish() {
  42. state_ = TASK_STATE_FINISHED;
  43. wake();
  44. return 0;
  45. }
  46. void SetTimeout(time_t ms) {
  47. timeout_ = ms;
  48. }
  49. int Wait(std::unique_lock<std::mutex>& locker) {
  50. is_wait_ = true;
  51. std::cv_status status = cond_.wait_for(locker, std::chrono::milliseconds(timeout_));
  52. is_wait_ = false;
  53. if (status == std::cv_status::timeout){
  54. SetErrno(ERR_TASK_TIMEOUT);
  55. return ERR_TASK_TIMEOUT;
  56. } else {
  57. state_ = TASK_STATE_FINISHED;
  58. }
  59. return 0;
  60. }
  61. void Lock() {
  62. ctx_mutex.lock();
  63. }
  64. void Unlock() {
  65. ctx_mutex.unlock();
  66. }
  67. protected:
  68. void wake() {
  69. if (is_wait_){
  70. is_wait_ = false;
  71. cond_.notify_all();
  72. }
  73. }
  74. public:
  75. std::mutex ctx_mutex; // provide a ctx mutex
  76. protected:
  77. State state_;
  78. int errno_;
  79. std::condition_variable cond_;
  80. bool is_wait_;
  81. time_t timeout_;
  82. };
  83. #endif // H_TASK_H_