worker.cpp 2.1 KB

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