//EvengtLoop.h/.cc
void EventLoop::loop()
{
...
while (!quit_)
{
...
pollReturnTime_ = poller_->poll(kPollTimeMs, &activeChannels_); //返回活动通道
...
// TODO sort channel by priority
eventHandling_ = true;
for (Channel* channel : activeChannels_) //遍历处理活动通道
{
currentActiveChannel_ = channel;
currentActiveChannel_->handleEvent(pollReturnTime_);
}
currentActiveChannel_ = NULL;
eventHandling_ = false;
//I/O线程执行channel的回调后,还可执行其他任务,如定时器任务
doPendingFunctors();
}
looping_ = false;
}
void EventLoop::doPendingFunctors()
{
std::vector<Functor> functors;
callingPendingFunctors_ = true;
{
//直接取出当前所有任务,可缩小临界区,减少阻塞
//使得其他线程可向pendingFunctors_中添加任务
MutexLockGuard lock(mutex_);
functors.swap(pendingFunctors_);
}
for (const Functor& functor : functors)
{
functor();
}
callingPendingFunctors_ = false;
}
void EventLoop::runInLoop(Functor cb)
{
if (isInLoopThread())
{
cb();//如果是当前I/O线程调用runInLoop,则同步调用cb
}
else
{
//如果是其他线程调用,则异步地将cb添加到队列
queueInLoop(std::move(cb));//pendingFunctors_.push_back(std::move(cb));
}
}
- runInLoop中的判断,可用于实现跨线程调用,如timerQueue中的addTimer调用了runInLoop,将定时器回调函数异步添加至I/O线程任务队列:
loop_->runInLoop(std::bind(&TimerQueue::addTimerInLoop, this, timer));
EventLoop线程封装。muduo采用one loop per thread, 即每个loop对应一个线程,所以可封装EventLoop线程
//EventLoopThread.h/.cc
class EventLoopThread : noncopyable
{
public:
typedef std::function<void(EventLoop*)> ThreadInitCallback;
...
EventLoop* startLoop(); //启动线程,该线程就成为IO线程
private:
void threadFunc(); //线程函数
EventLoop* loop_ GUARDED_BY(mutex_); //指向一个EventLoop对象
...
ThreadInitCallback callback_; //回调函数,在EventLoop::loop()事件循环之前被调用
};