-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventLoop.cpp
More file actions
199 lines (171 loc) · 5.22 KB
/
Copy pathEventLoop.cpp
File metadata and controls
199 lines (171 loc) · 5.22 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#include "EventLoop.h"
#include "Channel.h"
#include <sys/eventfd.h>
#include <sys/time.h>
#include <unistd.h>
#include <iostream>
int64_t EventLoop::nowMs() {
struct timeval tv;
gettimeofday(&tv, nullptr);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
EventLoop::EventLoop()
: epollFd_(epoll_create(1))
, events_(kInitEventsSize)
, threadId_(std::this_thread::get_id())
, wakeupFd_(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK))
{
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = nullptr;
epoll_ctl(epollFd_, EPOLL_CTL_ADD, wakeupFd_, &ev);
}
EventLoop::~EventLoop() {
close(epollFd_);
close(wakeupFd_);
}
bool EventLoop::isInLoopThread() const {
return threadId_ == std::this_thread::get_id();
}
void EventLoop::runInLoop(Functor cb) {
if (isInLoopThread()) {
cb();
} else {
queueInLoop(std::move(cb));
}
}
void EventLoop::queueInLoop(Functor cb) {
{
std::lock_guard<std::mutex> lock(mutex_);
pendingFunctors_.push_back(std::move(cb));
}
if (!isInLoopThread()) {
wakeup();
}
}
void EventLoop::wakeup() {
uint64_t one = 1;
ssize_t n = write(wakeupFd_, &one, sizeof(one));
(void)n;
}
void EventLoop::doPendingFunctors() {
std::vector<Functor> functors;
{
std::lock_guard<std::mutex> lock(mutex_);
functors.swap(pendingFunctors_);
}
for (const auto& func : functors) {
func();
}
}
void EventLoop::loop() {
while (true) {
int timeoutMs = 1000;
{
std::lock_guard<std::mutex> lock(timerMutex_);
if (!timers_.empty()) {
int64_t nextExpire = timers_.begin()->first;
int64_t now = nowMs();
timeoutMs = static_cast<int>(nextExpire - now);
if (timeoutMs < 0) timeoutMs = 0;
if (timeoutMs > 1000) timeoutMs = 1000;
}
}
int numEvents = epoll_wait(epollFd_, events_.data(), events_.size(), timeoutMs);
for (int i = 0; i < numEvents; i++) {
if (events_[i].data.ptr == nullptr) {
uint64_t buf;
ssize_t n = read(wakeupFd_, &buf, sizeof(buf));
(void)n;
continue;
}
auto channel = static_cast<Channel*>(events_[i].data.ptr);
channel->handleEvent(events_[i].events);
}
doPendingFunctors();
handleExpiredTimers();
}
}
void EventLoop::updateChannel(Channel *channel) {
int fd = channel->fd();
struct epoll_event ev;
ev.events = channel->events();
ev.data.ptr = channel;
int op;
bool isInEpoll = fdInEpoll_[fd];
if (channel->events() == 0) {
op = EPOLL_CTL_DEL;
fdInEpoll_[fd] = false;
} else if (isInEpoll) {
op = EPOLL_CTL_MOD;
} else {
op = EPOLL_CTL_ADD;
fdInEpoll_[fd] = true;
}
epoll_ctl(epollFd_, op, fd, &ev);
}
void EventLoop::removeChannel(Channel *channel) {
int fd = channel->fd();
removeTimer(fd);
if (fdInEpoll_.find(fd) == fdInEpoll_.end() || !fdInEpoll_[fd]) {
std::cout << " -> 跳过重复删除 fd=" << fd << std::endl;
activeChannels_.erase(fd);
return;
}
std::cout << "removeChannel fd=" << fd << std::endl;
epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, nullptr);
fdInEpoll_[fd] = false;
std::cout << " -> epoll DEL" << std::endl;
activeChannels_.erase(fd);
std::cout << " -> 从activeChannels_移除, 剩余活跃连接: " << activeChannels_.size() << std::endl;
}
void EventLoop::holdChannel(std::shared_ptr<Channel> channel) {
activeChannels_[channel->fd()] = channel;
}
void EventLoop::addTimer(int id, int64_t expireTime, Timer::TimerCallback cb) {
std::lock_guard<std::mutex> lock(timerMutex_);
removeTimerInLock(id);
auto timer = std::make_shared<Timer>(expireTime, std::move(cb));
timerMap_[id] = timer;
timers_.insert({expireTime, id});
}
void EventLoop::removeTimer(int id) {
std::lock_guard<std::mutex> lock(timerMutex_);
removeTimerInLock(id);
}
void EventLoop::removeTimerInLock(int id) {
auto it = timerMap_.find(id);
if (it != timerMap_.end()) {
int64_t expireTime = it->second->expireTime();
auto range = timers_.equal_range({expireTime, id});
for (auto iter = range.first; iter != range.second; ++iter) {
if (iter->second == id) {
timers_.erase(iter);
break;
}
}
timerMap_.erase(it);
}
}
void EventLoop::handleExpiredTimers() {
std::vector<Timer::TimerCallback> expiredCallbacks;
{
std::lock_guard<std::mutex> lock(timerMutex_);
int64_t now = nowMs();
while (!timers_.empty()) {
auto it = timers_.begin();
if (it->first > now) break;
int id = it->second;
timers_.erase(it);
auto timerIt = timerMap_.find(id);
if (timerIt != timerMap_.end()) {
expiredCallbacks.push_back(timerIt->second->callback());
timerMap_.erase(timerIt);
}
}
} // 锁释放
// 在锁外执行回调,彻底避免死锁
for (auto& cb : expiredCallbacks) {
if (cb) cb();
}
}