本文主要是介绍muduo网络库学习--EventLoop(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//EvengtLoop.h/.cc
void EventLoop::loop()
{...while (!quit_){...pollReturnTime_ = poller_->poll(kPollTimeMs, &activeChannels_); //返回活动通道...// TODO sort channel by priorityeventHandling_ = 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()事件循环之前被调用
};
这篇关于muduo网络库学习--EventLoop(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!