浅析muduo网络库

浅析muduo网络库之定时任务EventLoop

2018-01-09  本文已影响37人  谢昆明

上代码

EventLoop::EventLoop()
    timerQueue_(new TimerQueue(this)),
}

EventLoop内置了一个定时器队列timerQueue_

定时器任务


TimerId EventLoop::runAt(const Timestamp& time, const TimerCallback& cb)
{
  return timerQueue_->addTimer(cb, time, 0.0);
}

看看TimeQueue的构造函数声明

class TimerQueue : boost::noncopyable
{
  explicit TimerQueue(EventLoop* loop);
};

传递了一个EventLoop进去,可以猜测定时任务是在EventLoop里面执行的

看看TimerQueue的构造函数实现

TimerQueue::TimerQueue(EventLoop* loop)
  : loop_(loop),
    timerfd_(createTimerfd()),
    timerfdChannel_(loop, timerfd_)
{
  timerfdChannel_.setReadCallback(
      boost::bind(&TimerQueue::handleRead, this));
}

不出所料,创建了timerfd_timerfdChannel_,有回调函数是handleRead

那应该在handleRead调用定时任务

void TimerQueue::handleRead()
{


  readTimerfd(timerfd_, now);

  //.........
  for (std::vector<Entry>::iterator it = expired.begin();
      it != expired.end(); ++it)
  {
    it->second->run();
  }

}

这个run()其实是Timer::run()

class Timer
{
  void run() const
  {
    callback_();
  }
}

打赏

如果这篇文章解决了您的问题,让我买根烟抽抽。

支付宝.jpg 微信.jpg
上一篇下一篇

猜你喜欢

热点阅读