1
0

async.cpp 2.0 KB

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