1
0

EventLoopThreadPool_test.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. EventLoopThreadPool loop_threads(4);
  19. loop_threads.start(true);
  20. int thread_num = loop_threads.threadNum();
  21. for (int i = 0; i < thread_num; ++i) {
  22. EventLoopPtr loop = loop_threads.nextLoop();
  23. printf("worker[%d] tid=%ld\n", i, loop->tid());
  24. loop->runInLoop([loop](){
  25. // runEvery 1s
  26. loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100));
  27. });
  28. loop->queueInLoop([](){
  29. printf("queueInLoop tid=%ld\n", hv_gettid());
  30. });
  31. loop->runInLoop([](){
  32. printf("runInLoop tid=%ld\n", hv_gettid());
  33. });
  34. }
  35. // runAfter 10s
  36. loop_threads.loop()->setTimeout(10000, [&loop_threads](TimerID timerID){
  37. loop_threads.stop(false);
  38. });
  39. // wait loop_threads exit
  40. loop_threads.join();
  41. return 0;
  42. }