async.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. uint64_t m_count;
  23. io_thread ()
  24. {
  25. m_count=0;
  26. m_async.set(*this);
  27. m_async.set<io_thread,&io_thread::on_async>(this);
  28. m_async.start();
  29. m_thread=new std::thread(std::bind(&io_thread::run,this));
  30. }
  31. void on_async()
  32. {
  33. if(m_stop_flag.load())
  34. ev::dynamic_loop::break_loop(ev::ALL);
  35. ++m_count;
  36. }
  37. void run()
  38. {
  39. dynamic_loop::run(0);
  40. log_info("thread exit.");
  41. }
  42. void destroy()
  43. {
  44. m_thread->join();
  45. delete this;
  46. }
  47. void notify(int i)
  48. {
  49. if(i==0)
  50. {
  51. m_stop_flag.store(true);
  52. }
  53. m_async.send();
  54. }
  55. private:
  56. ~io_thread()
  57. {
  58. delete m_thread;
  59. }
  60. };
  61. int main()
  62. {
  63. // log_init("log.ini");
  64. std::vector<io_thread*> ivec;
  65. const int NUM_THREAD=4;
  66. for(int i=0;i<NUM_THREAD;i++)
  67. {
  68. ivec.push_back(new io_thread());
  69. }
  70. zclock c;
  71. uint64_t atps=0;
  72. uint64_t tps=0;
  73. for(uint64_t i=1;i<1e8;i++)
  74. {
  75. for(auto&t:ivec)
  76. {
  77. tps++;
  78. atps++;
  79. t->notify(i);
  80. }
  81. if((i-1)%1000==0 && c.count_ms()>1000)
  82. {
  83. std_info("tps=%ld,all=%ld",tps,atps);
  84. tps=0;
  85. c.reset();
  86. }
  87. }
  88. std::for_each(ivec.begin(),ivec.end(),[](io_thread*i){
  89. i->notify(0);
  90. i->destroy();
  91. std_info("thread_counter=%d",i->m_count);
  92. });
  93. return 0;
  94. }