htask.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. timeout_ = DEFAULT_TASK_TIMEOUT;
  21. }
  22. ~HTask() {
  23. }
  24. State GetState() {return state_;}
  25. int GetErrno() {return errno_;}
  26. void SetErrno(int errcode) {
  27. errno_ = errcode;
  28. if (errno_ != 0) {
  29. state_ = TASK_STATE_ERROR;
  30. }
  31. }
  32. virtual int Ready() {
  33. state_ = TASK_STATE_READY;
  34. return 0;
  35. }
  36. virtual int Exec() {
  37. state_ = TASK_STATE_EXECUTING;
  38. return 0;
  39. }
  40. virtual int Finish() {
  41. state_ = TASK_STATE_FINISHED;
  42. wake();
  43. return 0;
  44. }
  45. void SetTimeout(time_t ms) {
  46. timeout_ = ms;
  47. }
  48. int Wait(std::unique_lock<std::mutex>& locker) {
  49. std::cv_status status = cond_.wait_for(locker, std::chrono::milliseconds(timeout_));
  50. if (status == std::cv_status::timeout){
  51. SetErrno(ERR_TASK_TIMEOUT);
  52. return ERR_TASK_TIMEOUT;
  53. } else {
  54. state_ = TASK_STATE_FINISHED;
  55. }
  56. return 0;
  57. }
  58. void Lock() {
  59. ctx_mutex.lock();
  60. }
  61. void Unlock() {
  62. ctx_mutex.unlock();
  63. }
  64. protected:
  65. void wake() {
  66. cond_.notify_all();
  67. }
  68. public:
  69. std::mutex ctx_mutex; // provide a ctx mutex
  70. protected:
  71. State state_;
  72. int errno_;
  73. std::condition_variable cond_;
  74. time_t timeout_;
  75. };
  76. #endif // H_TASK_H_