-
Notifications
You must be signed in to change notification settings - Fork 0
/
Channel.h
86 lines (71 loc) · 2.84 KB
/
Channel.h
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
78
79
80
81
82
83
84
85
86
#ifndef SIMPLE_MUDUO_CHANNEL_H
#define SIMPLE_MUDUO_CHANNEL_H
#include <functional>
#include <memory>
#include "noncopyable.h"
#include "Timestamp.h"
namespace simple_muduo{
// EventLoop Channel Poller三着紧密相连,EventLoop是 Channel与Poller之间的桥梁
// Channel理解为通道 封装了sockfd和其感兴趣的event(io事件) 绑定了Poller返回的具体事件
// Channel是一个管理类
// Channel 与 EventLoop
// Poller 与 EventLoop
class EventLoop;
class Channel : noncopyable
{
public:
using EventCallback = std::function<void()>;
using ReadEventCallback = std::function<void(Timestamp)>;
Channel(EventLoop* loop, int fd);
~Channel();
// fd得到Poller通知以后,处理事件 handleEvent在EventLoop::Loop()中调用
void handleEvent(Timestamp receiveTime);
// 设置各种事件处理的回调函数,主要是用户设置事件处理的逻辑
void setReadCallback(ReadEventCallback cb) { readCallback_ = std::move(cb); }
void setWriteCallback(EventCallback cb) { writeCallback_ = std::move(cb); }
void setCloseCallback(EventCallback cb) { closeCallback_ = std::move(cb); }
void setErrorCallback(EventCallback cb) { errorCallback_ = std::move(cb); }
// 当channel被手动remove后,channel还在执行操作。
void tie(const std::shared_ptr<void>&);
int fd() const {return fd_;}
int events() const { return events_; }
void set_revents(int revt) { revents_ = revt; }
// 设置fd相应的事件状态 相当于epoll_ctl add delete
void enableReading() { events_ |= kReadEvent; update(); }
void disableReading() { events_ &= ~kReadEvent; update(); }
void enableWriting() { events_ |= kWriteEvent; update(); }
void disableWriting() { events_ &= ~kWriteEvent; update(); }
void disableAll() { events_ = kNoneEvent; update(); }
// 返回fd当前的事件状态
bool isNoneEvent() const { return events_ == kNoneEvent; }
bool isWriting() const { return events_ & kWriteEvent; }
bool isReading() const { return events_ & kReadEvent; }
int index() { return index_; }
void set_index(int idx) { index_ = idx; }
// one loop per thread
EventLoop *ownerLoop() { return loop_; }
void remove();
private:
void update();
void handleEventWithGuard(Timestamp receiveTime);
static const int kNoneEvent;
static const int kReadEvent;
static const int kWriteEvent;
EventLoop* loop_;
// Poller监听的fd
const int fd_;
// 注册fd感兴趣的事件
int events_;
// Poller返回的具体发生的事件
int revents_;
int index_;
std::weak_ptr<void> tie_;
bool tied_;
// 因为channel通道里可获知fd最终发生的具体的事件events,所以它负责调用具体事件的回调操作
ReadEventCallback readCallback_;
EventCallback writeCallback_;
EventCallback closeCallback_;
EventCallback errorCallback_;
};
}
#endif //SIMPLE_MUDUO_CHANNEL_H