1
0

EventLoopThreadPool_test.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * EventLoopThreadPool_test.cpp
  3. *
  4. * @build
  5. * make libhv && sudo make install
  6. * g++ -std=c++11 EventLoopThreadPool_test.cpp -o EventLoopThreadPool_test -I/usr/local/include/hv -lhv -lpthread
  7. *
  8. */
  9. #include "hv.h"
  10. #include "EventLoopThreadPool.h"
  11. using namespace hv;
  12. static void onTimer(TimerID timerID, int n) {
  13. printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n);
  14. }
  15. int main(int argc, char* argv[]) {
  16. HV_MEMCHECK;
  17. printf("main tid=%ld\n", hv_gettid());
  18. EventLoopPtr master_loop(new EventLoop);
  19. EventLoopThreadPool loop_threads(master_loop, 4);
  20. loop_threads.start(true);
  21. int thread_num = loop_threads.thread_num();
  22. for (int i = 0; i < thread_num; ++i) {
  23. EventLoopPtr loop = loop_threads.nextLoop();
  24. printf("worker[%d] tid=%ld\n", i, loop->tid());
  25. loop->runInLoop([loop](){
  26. // runEvery 1s
  27. loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100));
  28. });
  29. loop->queueInLoop([](){
  30. printf("queueInLoop tid=%ld\n", hv_gettid());
  31. });
  32. loop->runInLoop([](){
  33. printf("runInLoop tid=%ld\n", hv_gettid());
  34. });
  35. }
  36. // runAfter 10s
  37. master_loop->setTimeout(10000, [&loop_threads](TimerID timerID){
  38. EventLoopPtr master_loop = loop_threads.loop();
  39. master_loop->stop();
  40. loop_threads.stop(false);
  41. });
  42. // master_loop run in main thread
  43. master_loop->run();
  44. // wait loop_threads exit
  45. loop_threads.join();
  46. return 0;
  47. }