muduo网络库学习--EventLoop(二)

//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()事件循环之前被调用
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值