-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventLoop.hpp
More file actions
77 lines (57 loc) · 2.48 KB
/
Copy pathEventLoop.hpp
File metadata and controls
77 lines (57 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#pragma once
#include <functional>
#include <vector>
#include <atomic>
#include <memory>
#include <mutex>
#include "noncopyable.hpp"
#include "Timestamp.hpp"
#include "CurrentThread.hpp"
class Channel;
class Poller;
// 事件循环类,主要包含了 Channel 和 Poller 两个大循环类
// Poller (epoll的抽象)
// Channel 封装了 fd, 感兴趣的event, 真实发生的 revent
class EventLoop : noncopyable
{
public:
using Functor = std::function<void()>;
EventLoop();
~EventLoop();
// 开启事件循环
void loop();
// 退出事件循环
void quit();
Timestamp pollRetuenTime() const { return pollRetuenTime_; }
// 在当前的 loop 中执行 cb
void runInLoop(Functor cb);
// 把 cb 放入队列中,唤醒 loop 所在的线程,执行 cb
void queueInLoop(Functor cb);
// 用来唤醒 loop 所在线程的
void wakeup();
// Eventloop 的方法 => Poller的方法
void updateChannel( Channel *channel );
void removeChannel( Channel *channel );
bool hasChannel( Channel *channel );
// 判断 EventLoop 对象是否在自己的线程里面
bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); }
private:
void handleRead(); //wake up
void doPendingFunctors(); // 执行回调
using ChannelList = std::vector<Channel *>;
std::atomic<bool> looping_; // 标识是否运行 loop
std::atomic<bool> quit_; // 标志退出loop循环
const pid_t threadId_; // 记录当前 loop 所在线程的 Id
Timestamp pollRetuenTime_; // poller返回发生事件的channels的时间点
std::unique_ptr<Poller> poller_;
// 主要作用,通过 eventfd 系统调用创建一个本地的 fd,专门用于唤醒 epoll_wait
// 当 mainloop 获取一个新用户的cahnnel,通过轮询算法选择一个 subloop
// 通过该成员唤醒 subloop
int wakeupFd_;
std::unique_ptr<Channel> wakeupChannel_; // 这个 Channel 是用于管理 wakeupFd的
ChannelList activeChannels_; // EventLoop 管理的所有 fd
// Channel *currentActiveChannel_; // 当前活跃的 Channel
std::atomic<bool> callingPendingFunctors_; // 标识当前loop是否有需要执行的回调操作
std::vector<Functor> pendingFunctors_; // 存储 loop 需要执行的所有回调操作,主要是subloop被mainloop唤醒之后要做的操作
std::mutex mutex_; // 互斥锁,用来保护上面 vector 容器的线程安全操作
};