zloop.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #ifndef _zloop_hpp_
  2. #define _zloop_hpp_
  3. #include <vector>
  4. #include <list>
  5. #include <atomic>
  6. #include <mutex>
  7. #include <assert.h>
  8. #include <ev++.h>
  9. struct zloop_base:ev::dynamic_loop
  10. {
  11. std::atomic<bool> m_stop_flag{false};
  12. ev::async m_async;
  13. int check_stop_flag()
  14. {
  15. if(!m_stop_flag.load())
  16. return 0;
  17. break_loop(ev::ALL);
  18. return 1;
  19. }
  20. virtual void on_async_0(){}
  21. void async_stop()
  22. {
  23. m_stop_flag.store(true);
  24. m_async.send();
  25. }
  26. zloop_base()
  27. {
  28. m_async.set(*this);
  29. m_async.set<zloop_base,&zloop_base::on_async_0>(this);
  30. m_async.start();
  31. }
  32. ~zloop_base()
  33. {
  34. m_async.stop();
  35. }
  36. };
  37. template<typename NT>
  38. struct zloop:zloop_base
  39. {
  40. std::mutex m_mutex;
  41. std::list<NT> m_async_list;
  42. virtual void on_async_0()
  43. {
  44. if(check_stop_flag())
  45. return;
  46. std::list<NT> async_list;
  47. {
  48. std::unique_lock<std::mutex> _lock(m_mutex);
  49. m_async_list.swap(async_list);
  50. }
  51. on_async(async_list);
  52. }
  53. virtual void on_async(const std::list<NT>&nt){}
  54. void async_request(NT tk)
  55. {
  56. {
  57. std::unique_lock<std::mutex> _lock(m_mutex);
  58. m_async_list.push_back(tk);
  59. }
  60. m_async.send();
  61. }
  62. zloop()
  63. {
  64. }
  65. ~zloop()
  66. {
  67. }
  68. };
  69. #endif