async.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #include <log.h>
  2. #include <unistd.h>
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #include <vector>
  6. #include <list>
  7. #include <thread>
  8. #include <atomic>
  9. #include <algorithm>
  10. #define EV_MULTIPLICITY 1
  11. #define EV_SIGNAL_ENABLE 1
  12. #define EV_ASYNC_ENABLE 1
  13. #include <ev++.h>
  14. #include <clock.h>
  15. #include <zio.h>
  16. #include <znet.h>
  17. struct io_thread:ev::dynamic_loop
  18. {
  19. std::atomic<bool> m_stop_flag{false};
  20. std::thread*m_thread;
  21. ev::async m_async;
  22. ev::io m_io;
  23. ev::timer m_timer;
  24. uint64_t m_count;
  25. io_thread ()
  26. {
  27. m_count=0;
  28. //异步
  29. m_async.set(*this);
  30. m_async.set<io_thread,&io_thread::on_async>(this);
  31. m_async.start();
  32. //tiemr..
  33. //set loop
  34. m_timer.set(*this);
  35. m_timer.set<io_thread,&io_thread::on_timer>(this);
  36. m_thread=new std::thread(std::bind(&io_thread::run,this));
  37. m_timer.start(2,0);
  38. }
  39. void on_async()
  40. {
  41. if(m_stop_flag.load())
  42. ev::dynamic_loop::break_loop(ev::ALL);
  43. ++m_count;
  44. std_info("on_async%d:%d",std::this_thread::get_id(),m_count);
  45. }
  46. void on_timer()
  47. {
  48. std_info("on_timer....");
  49. m_timer.start(2,0);
  50. }
  51. void run()
  52. {
  53. dynamic_loop::run(0);
  54. //log_info("thread exit.");
  55. std_info("thread exit.%d",std::this_thread::get_id());
  56. }
  57. void destroy()
  58. {
  59. m_thread->join();
  60. delete this;
  61. }
  62. void notify(int i)
  63. {
  64. if(i==0)
  65. {
  66. m_stop_flag.store(true);
  67. }
  68. m_async.send();
  69. }
  70. private:
  71. ~io_thread()
  72. {
  73. delete m_thread;
  74. }
  75. };
  76. int main()
  77. {
  78. // log_init("log.ini");
  79. std::vector<io_thread*> ivec;
  80. const int NUM_THREAD=4;
  81. for(int i=0;i<NUM_THREAD;i++)
  82. {
  83. ivec.push_back(new io_thread());
  84. }
  85. zclock c;
  86. uint64_t atps=0;
  87. uint64_t tps=0;
  88. for(uint64_t i=1;i<1e8;i++)
  89. {
  90. for(auto&t:ivec)
  91. {
  92. tps++;
  93. atps++;
  94. t->notify(i);
  95. }
  96. if((i-1)%1000==0 && c.count_ms()>1000)
  97. {
  98. std_info("tps=%ld,all=%ld",tps,atps);
  99. tps=0;
  100. c.reset();
  101. }
  102. }
  103. std::for_each(ivec.begin(),ivec.end(),[](io_thread*i){
  104. i->notify(0);
  105. i->destroy();
  106. std_info("thread_counter=%d",i->m_count);
  107. });
  108. return 0;
  109. }