1
0

async.cpp 2.1 KB

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