worker.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #ifndef _WORKER_HPP_
  2. #define _WORKER_HPP_
  3. #include <ev++.h>
  4. #include <atomic>
  5. #include <thread>
  6. #include <vector>
  7. #include <zloop.h>
  8. struct task
  9. {
  10. uint32_t m_cmd_code;
  11. uint32_t m_hash_id;
  12. task(uint32_t hash_id,uint32_t cmd_code)
  13. :m_cmd_code(cmd_code)
  14. ,m_hash_id(hash_id)
  15. {
  16. }
  17. task()
  18. {}
  19. void destroy()
  20. {
  21. delete this;
  22. }
  23. template<typename T> const T&body()const
  24. {
  25. return *(T*)this;
  26. }
  27. template<typename T> T&body()
  28. {
  29. return *(T*)this;
  30. }
  31. template<typename T> static task*alloc()
  32. {
  33. return new T();
  34. }
  35. virtual ~task(){}
  36. };
  37. struct area_business;
  38. struct message_change_business:task
  39. {
  40. int area_id;
  41. std::atomic<int> ref_count;
  42. std::vector<area_business*> del_list,add_list,new_list;
  43. };
  44. struct message_change_card_display:task
  45. {
  46. uint64_t m_card_id;
  47. uint16_t m_display;
  48. };
  49. struct worker
  50. {
  51. virtual void stop()=0;
  52. virtual void request(task*tk)=0;
  53. virtual void broadcast(task*tk)
  54. {
  55. }
  56. virtual int num_thread()
  57. {
  58. return 1;
  59. }
  60. static worker*instance();
  61. };
  62. struct loop_thread:zloop<task*>
  63. {
  64. std::unique_ptr<std::thread> m_thread;
  65. loop_thread ();
  66. ~loop_thread();
  67. void run();
  68. void stop();
  69. void join();
  70. void on_async(const std::list<task*>&task_list);
  71. virtual void loop_init();
  72. virtual void do_task(task&t)=0;
  73. };
  74. #endif