Debian Codegraph @

third-party/libhv-v1.3.3/docs/cn/EventLoop.md

raw
1 事件循环类
2
3 ```c++
4
5 class EventLoop {
6
7 // 返回底层的loop结构体指针
8 hloop_t* loop();
9
10 // 运行
11 void run();
12 // 停止
13 void stop();
14 // 暂停
15 void pause();
16 // 继续
17 void resume();
18
19 // 设置定时器
20 TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID);
21
22 // 设置一次性定时器
23 TimerID setTimeout(int timeout_ms, TimerCallback cb);
24
25 // 设置永久性定时器
26 TimerID setInterval(int interval_ms, TimerCallback cb);
27
28 // 杀掉定时器
29 void killTimer(TimerID timerID);
30
31 // 重置定时器
32 void resetTimer(TimerID timerID, int timeout_ms = 0);
33
34 // 返回事件循环所在的线程ID
35 long tid();
36
37 // 是否在事件循环所在线程
38 bool isInLoopThread();
39
40 // 断言在事件循环所在线程
41 void assertInLoopThread();
42
43 // 运行在事件循环里
44 void runInLoop(Functor fn);
45
46 // 队列在事件循环里
47 void queueInLoop(Functor fn);
48
49 // 投递一个事件到事件循环
50 void postEvent(EventCallback cb);
51
52 };
53
54 class EventLoopThread {
55
56 // 返回事件循环指针
57 const EventLoopPtr& loop();
58
59 // 返回底层的loop结构体指针
60 hloop_t* hloop();
61
62 // 是否运行中
63 bool isRunning();
64
65 /* 开始运行
66 * wait_thread_started: 是否阻塞等待线程开始
67 * pre: 线程开始后执行的函数
68 * post: 线程结束前执行的函数
69 */
70 void start(bool wait_thread_started = true,
71 Functor pre = Functor(),
72 Functor post = Functor());
73
74 // 停止运行
75 void stop(bool wait_thread_stopped = false);
76
77 // 等待线程退出
78 void join();
79
80 };
81
82 class EventLoopThreadPool {
83
84 // 获取线程数量
85 int threadNum();
86
87 // 设置线程数量
88 void setThreadNum(int num);
89
90 // 返回下一个事件循环对象
91 // 支持轮询、随机、最少连接数等负载均衡策略
92 EventLoopPtr nextLoop(load_balance_e lb = LB_RoundRobin);
93
94 // 返回索引的事件循环对象
95 EventLoopPtr loop(int idx = -1);
96
97 // 返回索引的底层loop结构体指针
98 hloop_t* hloop(int idx = -1);
99
100 /* 开始运行
101 * wait_threads_started: 是否阻塞等待所有线程开始
102 * pre: 线程开始后执行的函数
103 * post: 线程结束前执行的函数
104 */
105 void start(bool wait_threads_started = false,
106 std::function<void(const EventLoopPtr&)> pre = NULL,
107 std::function<void(const EventLoopPtr&)> post = NULL);
108
109 // 停止运行
110 void stop(bool wait_threads_stopped = false);
111
112 // 等待所有线程退出
113 void join();
114
115 };
116
117 ```
118
119 测试代码见:
120
121 - [evpp/EventLoop_test.cpp](../../evpp/EventLoop_test.cpp)
122 - [evpp/EventLoopThread_test.cpp](../../evpp/EventLoopThread_test.cpp)
123 - [evpp/EventLoopThreadPool_test.cpp](../../evpp/EventLoopThreadPool_test.cpp)