worker.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #include <list>
  2. #include <vector>
  3. #include <mutex>
  4. #include <atomic>
  5. #include <memory>
  6. #include <thread>
  7. #include <ev++.h>
  8. #include "log.h"
  9. #include "worker.h"
  10. #include "message.h"
  11. #include "card.h"
  12. #include "zloop.h"
  13. struct worker_thread: zloop<task*>
  14. {
  15. std::unique_ptr<std::thread> m_thread;
  16. card_list*m_card_list;
  17. worker_thread ()
  18. {
  19. m_thread.reset(new std::thread(std::bind(&worker_thread::run,this)));
  20. m_card_list=card_list::instance();//*********
  21. }
  22. void run()
  23. {
  24. ev::dynamic_loop::run(0);
  25. log_info("worker_thread exit.");
  26. }
  27. virtual void on_async(const std::list<task*>&task_list)
  28. {
  29. for(task*t:task_list)
  30. {
  31. do_task(*t);
  32. free(t);
  33. }
  34. }
  35. void do_task(const task&t)
  36. {
  37. switch(t.m_cmd_code)
  38. {
  39. case 0x843b://tof
  40. case 0x863b://tdoa
  41. log_info("card loc message%04X",t.m_cmd_code);
  42. m_card_list->on_message(this,t.body<message_locinfo>(),false);
  43. //card_message::on_loc_message(this,t.m_param1);
  44. break;
  45. case 0x853b://tof his
  46. case 0x873b://tdoa his
  47. log_info("site history message%04X",t.m_cmd_code);
  48. m_card_list->on_message(this,t.body<message_locinfo>(),true);
  49. //site_message::on_sync(this,t.m_param1);
  50. break;
  51. case 0x804c://ctrl site message
  52. log_info("ctrl site message%04X",t.m_cmd_code);
  53. break;
  54. }
  55. }
  56. void join()
  57. {
  58. m_thread->join();
  59. }
  60. void stop()
  61. {
  62. async_stop();
  63. }
  64. };
  65. struct worker_impl:worker
  66. {
  67. std::vector<std::shared_ptr<worker_thread>> m_threads;
  68. std::atomic<int> m_init_flag{-2};
  69. virtual void stop()
  70. {
  71. for(auto&thr:m_threads)
  72. thr->stop();
  73. for(auto&thr:m_threads)
  74. thr->join();
  75. }
  76. worker_thread& hash(uint64_t i)
  77. {
  78. return *m_threads[i*2003%m_threads.size()].get();
  79. }
  80. virtual void request(task*t)
  81. {
  82. hash(t->m_hash_id).async_request(t);
  83. }
  84. void init(int num_thread)
  85. {
  86. int exp=-2;
  87. if(m_init_flag.compare_exchange_strong (exp,-1))
  88. {
  89. m_threads.resize(num_thread);
  90. for(int i=0;i<num_thread;i++)
  91. {
  92. m_threads[i].reset(new worker_thread());
  93. }
  94. m_init_flag.store(0);
  95. }
  96. while(0!=m_init_flag.load())
  97. std::this_thread::yield();
  98. }
  99. };
  100. worker_impl _worker_impl;
  101. worker*worker::instance()
  102. {
  103. _worker_impl.init(4);
  104. return &_worker_impl;
  105. }