handler.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <functional>
  5. #include "QtCore/qobject.h"
  6. #include "ybase/error.h"
  7. #include "ybase/singleton.hpp"
  8. #include "yutil/thread.h"
  9. #include "yutil/queue.hpp"
  10. #include "yutil/system.h"
  11. namespace ylib
  12. {
  13. template<typename DATA> class IHandler;
  14. template<typename DATA>
  15. class Handler: public ylib::error_base, public ylib::singleton<ylib::Handler<DATA>>, public ylib::ithread
  16. {
  17. friend class ylib::singleton<ylib::Handler<DATA>>;
  18. public:
  19. struct QueueInfo
  20. {
  21. int type = 0;
  22. int cmd = 0;
  23. DATA data;
  24. uint32 index = 0;
  25. };
  26. public:
  27. void start() {
  28. ylib::ithread::start();
  29. }
  30. void stop() {
  31. ylib::ithread::stop();
  32. ylib::ithread::wait();
  33. }
  34. void regist(std::function<ylib::IHandler<DATA>*(int type)> callback) {
  35. m_callback = callback;
  36. };
  37. uint32 push(int type, int cmd,const DATA& data = DATA())
  38. {
  39. uint32 index = ++m_queue_index;
  40. QueueInfo info;
  41. info.index = index;
  42. info.type = (int)type;
  43. info.cmd = (int)cmd;
  44. info.data = data;
  45. m_queue.push(info);
  46. return index;
  47. }
  48. void wait(uint32 index, uint32 wait_sec = 10){
  49. for (size_t i = 0; i < wait_sec * 10; i++)
  50. {
  51. if (index <= m_current_queue_index)
  52. return;
  53. system::sleep_msec(100);
  54. }
  55. }
  56. // 获取已处理到的类型索引号
  57. uint32 currentIndex() {
  58. return m_current_queue_index;
  59. }
  60. virtual bool run() override {
  61. QueueInfo info;
  62. IHandler<DATA>* handler = nullptr;
  63. while (m_queue.pop(info))
  64. {
  65. handler = m_callback((int)info.type);
  66. handler->exec(info);
  67. delete handler;
  68. m_current_queue_index = info.index;
  69. }
  70. system::sleep_msec(100);
  71. return true;
  72. }
  73. private:
  74. Handler()
  75. {
  76. }
  77. ~Handler()
  78. {
  79. }
  80. private:
  81. // 任务队列
  82. ylib::queue<QueueInfo> m_queue;
  83. // 已处理索引号
  84. uint32 m_current_queue_index = 0;
  85. // 索引号
  86. uint32 m_queue_index = 0;
  87. // 回调
  88. std::function<ylib::IHandler<DATA>*(int type)> m_callback;
  89. };
  90. template<typename DATA>
  91. class IHandler
  92. {
  93. public:
  94. virtual void exec(const struct ylib::Handler<DATA>::QueueInfo& info) = 0;
  95. };
  96. }