-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventLoop.cpp
73 lines (62 loc) · 1.71 KB
/
EventLoop.cpp
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
//
// Created by parallels on 2020/1/20.
//
#include "EventLoop.h"
#include "UtilFun.h"
#include <sys/eventfd.h>
#include "UtilFun.h"
ssize_t writen(int fd, char *buff, size_t n);
int createEventfd() {
int evtfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (evtfd < 0) {
ERR_MSG("create eventfd error");
exit(0);
}
return evtfd;
}
//向event_fd_发送一个信号使线程从epoll_wait状态激活,同时在server中更新了新的epoll,以执行新的事件
void EventLoop::wakeup() {
uint64_t one = 1;
ssize_t n = writen2(event_fd_, (char*)(&one), sizeof one);
if (n != sizeof one) {
printf("wakeup a thread error\n");
}
else
if(DEBUG)
printf("wakeup a thread\n");
fflush(stdout);
}
EventLoop::EventLoop() :
event_fd_(createEventfd()), wait_Task_(new Task(this, event_fd_)), epoll_(new Epoll), looping_(false), quit_(false) {
wait_Task_->setReadHandle(std::bind(&EventLoop::readHandle, this));
//epoll_->addEpoll(wait_Task_);
}
EventLoop::~EventLoop() {
printf("delete loop\n");
fflush(stdout);
}
void EventLoop::readHandle() {
uint64_t one = 1;
ssize_t n = readn(event_fd_, &one, sizeof one);
if (n != sizeof one) {
printf("wakeup error\n");
//looping_ = true;
}
else {
if(DEBUG)
printf("wakeup success\n");
looping_ = true;
}
fflush(stdout);
//wait_Task_->epoll_->addEpoll(EPOLLIN);
}
//事件循环
void EventLoop::loop() {
//epoll_->addEpoll(wait_Task_);
while(!quit_) {
fflush(stdout);
std::vector<std::shared_ptr<Task> > req = epoll_->poll();
for(auto &it : req) it->eventHandle();
epoll_->handleTimer();
}
}