You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.9 KiB

  1. #include <iostream>
  2. #include <event2/event.h>
  3. #include <string.h>
  4. #include <thread>
  5. #ifdef _WIN32
  6. #else
  7. #include <signal.h>
  8. #endif // !_WIN32
  9. using namespace std;
  10. static timeval t1 = {1,0};
  11. void timer1(int sock,short which, void *arg){
  12. cout << "[timer1]" << flush;
  13. event* ev = (event*)arg;
  14. if(!evtimer_pending(ev,&t1) ){
  15. evtimer_del(ev);
  16. evtimer_add(ev,&t1);
  17. }
  18. }
  19. void timer2(int sock,short which, void *arg){
  20. cout << "[timer2]" << flush;
  21. this_thread::sleep_for(3000ms); //c++ 11
  22. }
  23. void timer3(int sock,short which, void *arg){
  24. cout << "[timer3]" << flush;
  25. }
  26. int main(int agrc,char** agrv){
  27. #ifdef _WIN32
  28. //初始化socket库
  29. WSADATA wsa;
  30. WSAStartup(MAKEWORD(2, 2), &wsa);
  31. #else
  32. if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { //忽略管道信号,发送数据给已关闭的socket,会飞掉!
  33. return 1;
  34. }
  35. #endif
  36. event_base *base = event_base_new();
  37. //定时器
  38. cout << "test timer" << endl;
  39. //非持久定时器 只进入一次
  40. event* evl = evtimer_new(base ,timer1,event_self_cbarg());
  41. if(evl == NULL){
  42. cout << "evtimer_new timer1 failed!" <<endl;
  43. return -1;
  44. }
  45. evtimer_add(evl,&t1);
  46. static timeval t2;
  47. t2.tv_sec = 1;
  48. t2.tv_usec = 200000; //微秒
  49. event *ev2 = event_new(base,-1,EV_PERSIST,timer2,0);
  50. event_add(ev2,&t2);
  51. //超时性能优化,默认event用二叉堆存储,插入删除 时间复杂度为O(logN)
  52. //优化到双向队列 插入删除O(1)
  53. event *ev3 = event_new(base,-1,EV_PERSIST,timer3,0);
  54. static timeval tv_in = {3,0};
  55. const timeval * t3;
  56. t3 = event_base_init_common_timeout(base,&tv_in);
  57. event_add(ev3,t3);
  58. //进入事件主循环
  59. event_base_dispatch(base);
  60. event_free(evl);
  61. event_free(ev2);
  62. event_base_free(base);
  63. return 0;
  64. }