深入了解muduo库:EventLoop类
EventLoop类
class EventLoopThread {
private:
using ChannelList = std::vector<Channel*>;
ChannelList activeChannels_;
int wakeupFd_;
public:
using Functor = std::function<void()>;
EventLoop* startLoop();
void wakeup();
void runInLoop(Functor cb);
void queueInLoop(Functor cb);
void loop();
};
queueInLoop()
queueInLoop
有两个作用:一是供该loop所属线程调用(在写操作完成时,线程并不会马上执行写回调函数,而是先放入队列,目的是为了尽快执行完本次epoll_wait返回的事件,避免写回调事件占用时间过长而影响服务端对客户端的响应);二是供其他线程调用,将回调函数放入队列,并唤醒该loop所属线程,让它亲自执行回调函数(同样是基于one loop per thread
思想) void EventLoop::queueInLoop(Functor cb)
{
{
std::unique_lock<std::mutex> lock(mutex_);
pendingFunctors_.emplace_back(cb);
}
if (!isInLoopThread() || callingPendingFunctors_) {
wakeup();
}
}
loop
loop
是工作线程的主要执行函数,每次epoll_wait
返回时(其他线程唤醒本线程同样通过epoll_wait)执行一轮循环,处理epoll_wait
返回的事件以及调用queueInloop
放入队列中的回调函数 while(!quit_) {
activeChannels_.clear();
pollReturnTime_ = poller_->poll(kPollTimeMs, &activeChannels_);
for (Channel *channel : activeChannels_) {
channel->handleEvent(pollReturnTime_);
}
doPendingFunctors();
}