muduo_net库源码分析(26-1

muduo网络库(1):muduo库整体框架 〇、背景 0.1、本文背景 在学习陈硕《Linux多线程服务端编程:使用muduo C++网络库》muduo源代码的过程中,感觉代码架构较复杂: 一是和boost相关的内容比较多,对现代C++编程理念不了解的人,可能感觉莫名其妙。(关于“现代C++”点击此处) 二是muduo的源代码中,虽然不考虑可移植性,但还是划分了很多小的类(Channel、Socket、TcpConnection、Acce... 阅读详情


  • Channel是selectable IO channel,负责注册与响应IO 事件,它不拥有file descriptor。

  • Channel是Acceptor、Connector、EventLoop、TimerQueue、TcpConnection的成员,生命期由后者控制。




时序图








EventLoop头文件

eventloop.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.

#ifndef MUDUO_NET_EVENTLOOP_H
#define MUDUO_NET_EVENTLOOP_H

#include <vector>

#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>

#include <muduo/base/CurrentThread.h>
#include <muduo/base/Thread.h>
#include <muduo/base/Timestamp.h>

namespace muduo
{
namespace net
{

class Channel; //聚合
class Poller; //组合
///
/// Reactor, at most one per thread.
///
/// This is an interface class, so don't expose too much details.
class EventLoop : boost::noncopyable
{
 public:
  EventLoop();
  ~EventLoop();  // force out-line dtor, for scoped_ptr members.

  ///
  /// Loops forever.
  ///
  /// Must be called in the same thread as creation of the object.
  ///
  void loop();

  void quit();

  ///
  /// Time when poll returns, usually means data arrivial.
  ///
  Timestamp pollReturnTime() const { return pollReturnTime_; }

  // internal usage
  void updateChannel(Channel* channel);     // 在Poller中添加(注册)或者更新通道
  void removeChannel(Channel* channel);     // 从Poller中移除通道

  /*断言是否在Loop 线程中*/
  void assertInLoopThread()
  {
      //如果不是在LoopThread中,终止程序
    if (!isInLoopThread())
    {
      abortNotInLoopThread();
    }
  }
  //判断是在当前线程是否在LoopThread中
  bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); }

  static EventLoop* getEventLoopOfCurrentThread();

 private:
  void abortNotInLoopThread();

  void printActiveChannels() const; // DEBUG

  typedef std::vector<Channel*> ChannelList;

  bool looping_; /*是否处于循环状态 atomic */
  bool quit_; /*是否退出Loop atomic */
  bool eventHandling_; /*当前是否处于事件处理的状态 atomic */
  const pid_t threadId_;        // 当前对象所属线程ID
  Timestamp pollReturnTime_;    //调用poller时候的返回时间
  boost::scoped_ptr<Poller> poller_; //poller对象,生命周期由EventLoop控制
  ChannelList activeChannels_;  // Poller返回的活动通道 ,
                                //就是活动状态的socket///typedef std::vector<Channel*> ChannelList;
  Channel* currentActiveChannel_;   // 当前正在处理的活动通道
};

}
}
#endif  // MUDUO_NET_EVENTLOOP_H

EventLoop源文件

EventLoop.cc


// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/EventLoop.h>

#include <muduo/base/Logging.h>
#include <muduo/net/Channel.h>
#include <muduo/net/Poller.h>

//#include <poll.h>

using namespace muduo;
using namespace muduo::net;

namespace
{
// 当前线程EventLoop对象指针
// 线程局部存储
__thread EventLoop* t_loopInThisThread = 0;

const int kPollTimeMs = 10000;
}

EventLoop* EventLoop::getEventLoopOfCurrentThread()
{
  return t_loopInThisThread;
}
/*
事件循环,该函数不能夸线程调用
只能在创建该对象的线程中调用
**/

EventLoop::EventLoop()
  : looping_(false),
    quit_(false),
    eventHandling_(false),
    threadId_(CurrentThread::tid()),
    poller_(Poller::newDefaultPoller(this)),
    currentActiveChannel_(NULL)
{
  LOG_TRACE << "EventLoop created " << this << " in thread " << threadId_;
  // 如果当前线程已经创建了EventLoop对象,终止(LOG_FATAL)
  if (t_loopInThisThread)
  {
    LOG_FATAL << "Another EventLoop " << t_loopInThisThread
              << " exists in this thread " << threadId_;
  }
  //如果当前线程没有创建EventLoop对象,则创建EventLoop对象,并且进行绑定
  else
  {
    t_loopInThisThread = this;
  }
}

EventLoop::~EventLoop()
{
  t_loopInThisThread = NULL;
}
 //这是IO线程
// 事件循环,该函数不能跨线程调用
// 只能在创建该对象的线程中调用
void EventLoop::loop()
{
//断言是否处于非循环状态
  assert(!looping_);
  // 断言当前处于创建该对象的线程中
  assertInLoopThread();
  looping_ = true;
  LOG_TRACE << "EventLoop " << this << " start looping";

  //::poll(NULL, 0, 5*1000);
  //循环直到退出
  while (!quit_)
  {
  //先清除活动通道
    activeChannels_.clear();
    //调用poller_->poll返回活动的通道 &activeChannels_以及poll返回的时间
    pollReturnTime_ = poller_->poll(kPollTimeMs, &activeChannels_);
    //++iteration_;
    //输出 处于活动状态的channel 到日志中
    if (Logger::logLevel() <= Logger::TRACE)
    {
      printActiveChannels();
    }
    // TODO sort channel by priority
    //当前事件处理状态设为true 
    eventHandling_ = true;
    //循环处理活动通道的事件
    for (ChannelList::iterator it = activeChannels_.begin();
        it != activeChannels_.end(); ++it)
    {
      currentActiveChannel_ = *it;
      currentActiveChannel_->handleEvent(pollReturnTime_);
    }
    //把当前的活动通道设为 NULL
    currentActiveChannel_ = NULL;
    //当前事件处理状态设为false
    eventHandling_ = false;
    //doPendingFunctors();
  }

  LOG_TRACE << "EventLoop " << this << " stop looping";
  looping_ = false;
}
 //该函数可以跨线程调用,这也是防止程序
void EventLoop::quit()
{
  quit_ = true; //由于是多线程访问这个变量,那么是否需要保护这个变量??,要的。但是quit_是布尔类型,是一种对布尔类型的变量操作是一种原子操作,所以我们不用显式的进行保护了
  if (!isInLoopThread())
  {
    //wakeup();
  }
}

// 用于注册或者更新 channel的事件
void EventLoop::updateChannel(Channel* channel)
{
  // 断言Channel 是否属于当前的EventLoop对象
  assert(channel->ownerLoop() == this);
  // 断言EventLoop所属的线程是当前的线程
  assertInLoopThread();
  // 更新channel的事件
  poller_->updateChannel(channel);
}

void EventLoop::removeChannel(Channel* channel)
{
  assert(channel->ownerLoop() == this);
  assertInLoopThread();
  if (eventHandling_)
  {
    assert(currentActiveChannel_ == channel ||
        std::find(activeChannels_.begin(), activeChannels_.end(), channel) == activeChannels_.end());
  }
  poller_->removeChannel(channel);
}

//如果不是在LoopThread线程中将终止线程
void EventLoop::abortNotInLoopThread()
{
  LOG_FATAL << "EventLoop::abortNotInLoopThread - EventLoop " << this
            << " was created in threadId_ = " << threadId_
            << ", current thread id = " <<  CurrentThread::tid();
}

/*打印处于活动状态的channel 到日志中*/
void EventLoop::printActiveChannels() const
{
  for (ChannelList::const_iterator it = activeChannels_.begin();
      it != activeChannels_.end(); ++it)
  {
    const Channel* ch = *it;
    LOG_TRACE << "{" << ch->reventsToString() << "} ";
  }
}




Poller头文件

poller.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is an internal header file, you should not include this.

#ifndef MUDUO_NET_POLLER_H
#define MUDUO_NET_POLLER_H

#include <vector>
#include <boost/noncopyable.hpp>

#include <muduo/base/Timestamp.h>
#include <muduo/net/EventLoop.h>

namespace muduo
{
namespace net
{

class Channel;

///
/// Base class for IO Multiplexing
///
/// This class doesn't own the Channel objects.
class Poller : boost::noncopyable
{
 public:
  typedef std::vector<Channel*> ChannelList;

  Poller(EventLoop* loop);
  virtual ~Poller();

  /// Polls the I/O events.
  /// Must be called in the loop thread.
  virtual Timestamp poll(int timeoutMs, ChannelList* activeChannels) = 0;

  /// Changes the interested I/O events.
  /// Must be called in the loop thread.
  virtual void updateChannel(Channel* channel) = 0;

  /// Remove the channel, when it destructs.
  /// Must be called in the loop thread.
  virtual void removeChannel(Channel* channel) = 0;

  static Poller* newDefaultPoller(EventLoop* loop);

  void assertInLoopThread()
  {
    ownerLoop_->assertInLoopThread();
  }

 private:
  EventLoop* ownerLoop_;    // Poller所属EventLoop
};

}
}
#endif  // MUDUO_NET_POLLER_H

Poller源文件

poller.cc

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/Poller.h>

using namespace muduo;
using namespace muduo::net;

Poller::Poller(EventLoop* loop)
  : ownerLoop_(loop)
{
}

Poller::~Poller()
{
}



PollPoller头文件

pollpoller.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is an internal header file, you should not include this.

#ifndef MUDUO_NET_POLLER_POLLPOLLER_H
#define MUDUO_NET_POLLER_POLLPOLLER_H

#include <muduo/net/Poller.h>

#include <map>
#include <vector>

struct pollfd;

namespace muduo
{
namespace net
{

///
/// IO Multiplexing with poll(2).
///
class PollPoller : public Poller
{
 public:

  PollPoller(EventLoop* loop);
  virtual ~PollPoller();

  /*返回活动的通道列表*/
  virtual Timestamp poll(int timeoutMs, ChannelList* activeChannels);
  virtual void updateChannel(Channel* channel);
  virtual void removeChannel(Channel* channel);

 private:
  void fillActiveChannels(int numEvents,
                          ChannelList* activeChannels) const;

  typedef std::vector<struct pollfd> PollFdList;
  typedef std::map<int, Channel*> ChannelMap; // key是文件描述符,value是Channel*
  PollFdList pollfds_; // 事件结构
  /*被关注的通道列表 , 不是活动的通道列表*/
  ChannelMap channels_;
};

}
}
#endif  // MUDUO_NET_POLLER_POLLPOLLER_H

PollPoller源文件

pollpoller.cc

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/poller/PollPoller.h>

#include <muduo/base/Logging.h>
#include <muduo/base/Types.h>
#include <muduo/net/Channel.h>

#include <assert.h>
#include <poll.h>

using namespace muduo;
using namespace muduo::net;

PollPoller::PollPoller(EventLoop* loop)
  : Poller(loop)
{
}

PollPoller::~PollPoller()
{
}

/*
真正的poll 函数,终于到主角了^<>^  ///
**/
Timestamp PollPoller::poll(int timeoutMs, ChannelList* activeChannels)
{
  // XXX pollfds_ shouldn't change
  int numEvents = ::poll(&*pollfds_.begin(), pollfds_.size(), timeoutMs);
  Timestamp now(Timestamp::now());
  //如果有活动事件 , 则填充到activeChannels 中去
  if (numEvents > 0)
  {
    LOG_TRACE << numEvents << " events happended";
    fillActiveChannels(numEvents, activeChannels);
  }
  else if (numEvents == 0)
  {
    LOG_TRACE << " nothing happended";
  }
  else
  {
    LOG_SYSERR << "PollPoller::poll()";
  }
  return now;
}

//填充活动通道
// activeChannels 活动通道
// pollfds_       已注册的事件集合
/*被关注的通道列表 , 不是活动的通道列表*/
void PollPoller::fillActiveChannels(int numEvents,
                                    ChannelList* activeChannels) const
{
  for (PollFdList::const_iterator pfd = pollfds_.begin();
      pfd != pollfds_.end() && numEvents > 0; ++pfd)
  {
    //返回活动的文件描述符
    if (pfd->revents > 0)
    {
      --numEvents;
      // 从关注列表channels_中找出 已产生事件 的fd---》channel
      ChannelMap::const_iterator ch = channels_.find(pfd->fd);
      // 断言是否已近到了channels_的尾部
      assert(ch != channels_.end());
      // 获取活动channel
      Channel* channel = ch->second; 
      // 断言channel的文件描述符是否和pfd 的描述符一致
      assert(channel->fd() == pfd->fd);
      // 设置channel的事件
      channel->set_revents(pfd->revents);
      // pfd->revents = 0;
      // 把活动channel 加入activeChannel容器
      activeChannels->push_back(channel);
    }
  }
}

/*
更行channel通道, 
**/
void PollPoller::updateChannel(Channel* channel)
{
  //断言实在LoopThread 当中
  Poller::assertInLoopThread();
  LOG_TRACE << "fd = " << channel->fd() << " events = " << channel->events();
  //如果新的通道,还没有注册事件
  if (channel->index() < 0)
  {
    // index < 0说明是一个新的通道
    // a new one, add to pollfds_ 
    //断言是新的通道
    assert(channels_.find(channel->fd()) == channels_.end());

    //注册事件
    struct pollfd pfd;
    pfd.fd = channel->fd();
    pfd.events = static_cast<short>(channel->events());
    pfd.revents = 0;
    pollfds_.push_back(pfd);
    //channel在pollfds中索引
    int idx = static_cast<int>(pollfds_.size())-1;
    //更新channel的索引
    channel->set_index(idx);
    //加入channels_ 的map中
    channels_[pfd.fd] = channel;
  }
  else
  {
    // update existing one
    //断言channel 已存在--》 channels_ ,index >0 < pollfds_.size()
    assert(channels_.find(channel->fd()) != channels_.end());
    assert(channels_[channel->fd()] == channel);
    int idx = channel->index();
    assert(0 <= idx && idx < static_cast<int>(pollfds_.size()));
    struct pollfd& pfd = pollfds_[idx];

    assert(pfd.fd == channel->fd() || pfd.fd == -channel->fd()-1);

    //下面才是真正的更新
    pfd.events = static_cast<short>(channel->events());
    //revents 貌似不用清零???
    pfd.revents = 0;
    // 将一个通道暂时更改为不关注事件,但不从Poller中移除该通道
    if (channel->isNoneEvent())
    {
      // ignore this pollfd
      // 暂时忽略该文件描述符的事件
      // 这里pfd.fd 可以直接设置为-1 , -1是为了排除0描述符的干扰
      pfd.fd = -channel->fd()-1; // 这样子设置是为了removeChannel优化
    }
  }
}

// 把channel 真正的从pollfds 中移除
void PollPoller::removeChannel(Channel* channel)
{
  Poller::assertInLoopThread();
  LOG_TRACE << "fd = " << channel->fd();
  assert(channels_.find(channel->fd()) != channels_.end());
  assert(channels_[channel->fd()] == channel);
  //要移除的channel一定是没有关注事件了 
  assert(channel->isNoneEvent());
  int idx = channel->index();
  assert(0 <= idx && idx < static_cast<int>(pollfds_.size()));
  const struct pollfd& pfd = pollfds_[idx]; (void)pfd;

  assert(pfd.fd == -channel->fd()-1 && pfd.events == channel->events());

  //1-----------》先把channel 从channels_中移除
  size_t n = channels_.erase(channel->fd());
  assert(n == 1); (void)n;
  //2-----------》如果是最后一个,则直接移除
  if (implicit_cast<size_t>(idx) == pollfds_.size()-1)
  {
    pollfds_.pop_back();
  }
  else
  {
    // 2----------》这里移除的算法复杂度是O(1),将待删除元素与最后一个元素交换再pop_back
    int channelAtEnd = pollfds_.back().fd;
    iter_swap(pollfds_.begin()+idx, pollfds_.end()-1);

    //channelAtEnd 是从 pollfds_ 里面拿出来的,所以可能是负数
    if (channelAtEnd < 0)
    {
      channelAtEnd = -channelAtEnd-1;
    }
    channels_[channelAtEnd]->set_index(idx);
    pollfds_.pop_back();
  }
}



Channel头文件

channel.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is an internal header file, you should not include this.

#ifndef MUDUO_NET_CHANNEL_H
#define MUDUO_NET_CHANNEL_H

#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>

#include <muduo/base/Timestamp.h>

namespace muduo
{
namespace net
{

class EventLoop;

///
/// A selectable I/O channel.
///
/// This class doesn't own the file descriptor.
/// The file descriptor could be a socket,
/// an eventfd, a timerfd, or a signalfd
class Channel : boost::noncopyable //不可拷贝的
{
 public:
  /*事件回调处理函数*/
  typedef boost::function<void()> EventCallback; 
  /*读事件的回调处理*/
  typedef boost::function<void(Timestamp)> ReadEventCallback;
  /*一个EventLoop 包含多个Channel , 一个channel只属于一个EventLoop
  Channel(n)-----> EventLoop
  */
  Channel(EventLoop* loop, int fd);
  //虚构函数没干什么事^V^
  ~Channel();

  void handleEvent(Timestamp receiveTime);

  /*回调函数的注册*/
  // 读的回调函数
  void setReadCallback(const ReadEventCallback& cb)
  { readCallback_ = cb; }
  // 写的回调函数
  void setWriteCallback(const EventCallback& cb)
  { writeCallback_ = cb; }
  // 关闭的回调函数
  void setCloseCallback(const EventCallback& cb)
  { closeCallback_ = cb; }
  // 出错的回调函数
  void setErrorCallback(const EventCallback& cb)
  { errorCallback_ = cb; }
//////////////////////////////////////////////////

  /*
这个函数下一节才开始分析^V^ ...
这个函数跟TcpConnection 生命周期是有关系的,为了防止在事件处理的时候
  **/
  /// Tie this channel to the owner object managed by shared_ptr,
  /// prevent the owner object being destroyed in handleEvent.
  void tie(const boost::shared_ptr<void>&);

  //channel 的描述符
  int fd() const { return fd_; }
  // channel注册的事件(关注的事件)
  int events() const { return events_; }

  // poller 实际返回的事件,
  void set_revents(int revt) { revents_ = revt; } // used by pollers

  //清空channel的事件
  // int revents() const { return revents_; }
  bool isNoneEvent() const { return events_ == kNoneEvent; }

  void enableReading() { events_ |= kReadEvent; update(); }
  // void disableReading() { events_ &= ~kReadEvent; update(); }
  void enableWriting() { events_ |= kWriteEvent; update(); }
  void disableWriting() { events_ &= ~kWriteEvent; update(); }
  void disableAll() { events_ = kNoneEvent; update(); }
  bool isWriting() const { return events_ & kWriteEvent; }

  // for Poller ; 在Poller数组中的索引
  int index() { return index_; }
  // 设置channel在poller的索引
  void set_index(int idx) { index_ = idx; }

  // for debug 事件的调试信息
  string reventsToString() const;

  void doNotLogHup() { logHup_ = false; }

  EventLoop* ownerLoop() { return loop_; }
  void remove();

 private:
  void update();
  void handleEventWithGuard(Timestamp receiveTime);

  //事件常量
  //没有事件就是说等于零
  static const int kNoneEvent;
  static const int kReadEvent;
  static const int kWriteEvent;

  EventLoop* loop_;         // 所属EventLoop
  const int  fd_;           // 文件描述符,但不负责关闭该文件描述符
  int        events_;       // 关注的事件
  int        revents_;      // poll/epoll返回的事件
  int        index_;        // used by Poller.表示在poll的事件数组中的序号
  bool       logHup_;       // for POLLHUP

  // 下面两个是负责生存期的控制
  boost::weak_ptr<void> tie_;
  bool tied_;


  bool eventHandling_;      // 是否处于处理事件中
  ReadEventCallback readCallback_;
  EventCallback writeCallback_;
  EventCallback closeCallback_;
  EventCallback errorCallback_;
};

}
}
#endif  // MUDUO_NET_CHANNEL_H

Channel源文件

channel.cc

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/base/Logging.h>
#include <muduo/net/Channel.h>
#include <muduo/net/EventLoop.h>

#include <sstream>

#include <poll.h>

using namespace muduo;
using namespace muduo::net;

const int Channel::kNoneEvent = 0; //没有事件
const int Channel::kReadEvent = POLLIN | POLLPRI; //产生量可读事件或者紧急数据
const int Channel::kWriteEvent = POLLOUT;

Channel::Channel(EventLoop* loop, int fd__)
  : loop_(loop),
    fd_(fd__),
    events_(0),
    revents_(0),
    index_(-1),  //没加入poller是,channel的索引为 -1 
    logHup_(true),
    tied_(false),
    eventHandling_(false)   //channel的事件处理状态初始化为 false
{
}

Channel::~Channel()
{
  assert(!eventHandling_);
}

void Channel::tie(const boost::shared_ptr<void>& obj)
{
  tie_ = obj;
  tied_ = true;
}

//更新channel的事件
void Channel::update()
{
  loop_->updateChannel(this);
}

// 调用这个函数之前确保调用disableAll
//  void disableAll() { events_ = kNoneEvent; update()-->assert(isNoneEvent()); }
void Channel::remove()
{
  assert(isNoneEvent());
  loop_->removeChannel(this);
}
/**
  当时到达时,调用事件处理函数handleEvent进行处理
*/
void Channel::handleEvent(Timestamp receiveTime)
{
  boost::shared_ptr<void> guard;
  if (tied_)
  {
    guard = tie_.lock();
    if (guard)
    {
      handleEventWithGuard(receiveTime);
    }
  }
  else
  {
    handleEventWithGuard(receiveTime);
  }
}

/**
 事件处理
**/
void Channel::handleEventWithGuard(Timestamp receiveTime)
{//把channel的事件处理状态设为 true
  eventHandling_ = true;
  //如果poller返回的channel 事件是pollhup挂断(写时才会产生),并且不是可读的 
  if ((revents_ & POLLHUP) && !(revents_ & POLLIN))
  {
    // 如果挂断了
    if (logHup_)
    {
      LOG_WARN << "Channel::handle_event() POLLHUP";
    }
    //如果挂断了,就返回closeCallback
    if (closeCallback_) closeCallback_();
  }

  //文件描述符不合法或者文件描述符没有打开
  if (revents_ & POLLNVAL)
  {
    LOG_WARN << "Channel::handle_event() POLLNVAL";
  }

  if (revents_ & (POLLERR | POLLNVAL))
  {
    if (errorCallback_) errorCallback_();
  }
  //可读事件 , 
  //POLLRDHUP :stream socket peer closed connection ,or shutdown writing half of connection
  //POLLPRI : there is urgent data to read 
  if (revents_ & (POLLIN | POLLPRI | POLLRDHUP))
  {
    if (readCallback_) readCallback_(receiveTime);
  }
  //可写事件
  if (revents_ & POLLOUT)
  {
    if (writeCallback_) writeCallback_();
  }
  //事件处理完后,把事件处理状态恢复为false状态
  eventHandling_ = false;
}

string Channel::reventsToString() const
{
  std::ostringstream oss;
  oss << fd_ << ": ";
  if (revents_ & POLLIN)
    oss << "IN ";
  if (revents_ & POLLPRI)
    oss << "PRI ";
  if (revents_ & POLLOUT)
    oss << "OUT ";
  if (revents_ & POLLHUP)
    oss << "HUP ";
  if (revents_ & POLLRDHUP)
    oss << "RDHUP ";
  if (revents_ & POLLERR)
    oss << "ERR ";
  if (revents_ & POLLNVAL)
    oss << "NVAL ";

  return oss.str().c_str();
}


最新《C++大并发高性能高可用可伸缩性服务器开发教程》 不可多得的教程,而且很少有讲解这部分的课程,需要的就下载吧! -------------课程目录-------------01大并发服务器架构介绍.avi 02大型网站架构演变过程.avi 03poll(一).avi 04poll(二)_.avi 05epoll(一).avi 06epoll(二).avi 07muduo介绍.avi 08面向对象编程风格.avi 09基于对象编程风格.avi 10... 阅读详情

相关推荐

muduo源码注释(非常详细)

个人在阅读muduo源码时,做的注释,非常详细,可以配合我的博客一起阅读。

muduo学习笔记:net部分之EventLoop

EventLoop的事件循环主要两个大部分:第一个部分,`Poller`监听`socketfd`、`timerfd`封装的`Channel`事件(网络事件、定时器事件),并执行对应IO事件的回调函数;第二个部分,在IO线程空闲时执行一些计算任务,充分利用线程资源。由于`Poller`是阻塞等待IO事件的,当有计算任务时需要被唤醒,使用eventfd的Channel的来实现。

热爱生活,忠于自己 919

字节开源 DeerFlow 2.0:从 Deep Research 到 Super Agent Harness 的进化之路

GitHub Trending 冠军项目,字节跳动完全开源的超级智能体框架。支持子代理、沙箱执行、长期记忆、技能扩展,可完成从几分钟到几小时的复杂任务。本文深度解析架构设计、安装实战、技能系统,并附上独家配置指南。

qq_38610923的博客 1727

多线程服务器编程之muduo中base库与net库详细注释

muduo学习 寒假写的,这个是github链接,之前一直写的比较乱,今天终于抽出时间整理了一下。 前言: 寒假在学习muduo的时候,将muduo中net库和base库源码进行了注释,基本所有的 重要代码都进行了详细注释,比较重要的类比如Eventloop类,Channel类部分函数 每行都进行了注释,还改进了几个小功能,比如Exception类增加了处理函数名的 功能,在使用时看起来更加方便...

RandyLambert的博客 496

高通thermal-engine.conf配置详解:从虚拟传感器到CPU频率控制的完整指南

本文深入解析了高通thermal-engine.conf配置文件的架构与调优方法。从虚拟传感器的加权融合原理,到监控算法与CPU频率控制的多级策略,提供了完整的配置详解与实战调试指南。文章旨在帮助开发者与高级用户掌握底层温控逻辑,在性能与散热间实现精准平衡,并详细介绍了日志调试与场景化配置等高级技巧。

weixin_28327051的博客 502

告别手动处理:用 Bruker NSMatlabUtilities 工具箱批量分析 AFM 力曲线数据的实战案例

本文介绍了如何使用 Bruker NSMatlabUtilities 工具箱实现 AFM 力曲线数据的批量分析,解决传统手动处理耗时且易出错的问题。通过实战案例展示工具箱的核心功能,包括数据读取、力曲线分析和可视化,帮助科研人员提升数据处理效率和准确性。

weixin_28362173的博客 218

muduo网络库net篇一:事件处理

时间有限,net篇采用边看代码边写。 net部分的类都定义在muduo::net命名空间下。 EventLoop类 这个类涉及好几个类: boost::scoped_ptr poller_; boost::scoped_ptr timerQueue_; boost::scoped_ptr wakeupChannel_; ChannelList activeChannels_;

月寒日暖的博客 345

55、宇宙微波背景辐射望远镜及其光学系统解析

本文详细解析了宇宙微波背景辐射(CMB)望远镜及其光学系统的设计与优化。内容涵盖折射与反射光学系统的特性、旁瓣控制技术、气球与地面观测系统的对比、探测器阵列的发展、光学系统设计流程以及不同观测场景下的光学系统选择。同时,文章展望了CMB望远镜光学系统的未来发展趋势,包括技术创新、多频段观测、国际合作与大型项目等。通过系统性的分析与对比,为CMB研究提供了全面的技术支持与理论基础。

f9g0h的博客 149

muduo学习笔记:net部分之实现TCP网络编程库-TcpClient

有了前文【muduo学习笔记:net部分之实现TCP网络编程库-Connector】的介绍,TcpClient的实现就不难了。muduo用TcpClient发起连接,TcpClient有一个Connector连接器,TCPClient使用Conneccor发起连接, 连接建立成功后, 用socket创建TcpConnection来管理连接, 每个TcpClient class只管理一个TcpConnecction,连接建立成功后设置相应的回调函数。很显然,TcpClient用来管理客户端连接,真正连接交给C

热爱生活,忠于自己 886

人工智能训练师三级考试大纲深度解读|理论+实操分值分布+六大模块占比

三级人工智能训练师考试分为理论和实操两大模块(各100分,合格线60分)。理论考试包含AI基础(30%)、数据标注(25%)、模型训练(20%)、测试(15%)和系统运维(10%),题型为客观题;实操考核侧重数据标注(40%)、模型测试(35%)和系统运维(25%),采用现场操作形式。复习应优先关注AI基础和数据标注等高分值模块,实操需重点掌握标准流程和结果准确性(占评分70%)。考试要求两模块均达标,理论侧重概念理解,实操强调规范执行与文档完整。

白话机器学习 1166

Android UI 组件系列(二):Button 进阶用法

在这篇博客中,我们深入探讨了 Button 的进阶用法,重点介绍了如何通过 事件处理 来响应用户的操作,如何使用 自定义样式 来提升按钮的外观,并利用 StateListDrawable 来管理按钮在不同状态下的表现。这些技巧能够帮助你打造更具交互性、视觉吸引力和动态响应的按钮,提升用户体验。

weixin_39339407的博客 1627

26muduo_net库源码分析(二)

1.类图 2.Channel (1)Channel是selectable IO channel,负责注册与响应IO事件,它不拥有filedescriptor。 (2)Channel是Acceptor、Connector、EventLoop、TimerQueue、TcpConnection的成员,生命期由后者控制。 3.时序图 4.代码 EvevtLoop.h

INGNIGHT的专栏 488

YOLOv11 改进 - 特征融合 | 替换 C3k2 涨点:GELAN 融合 CSP+ELAN 提精度

本文介绍了可编程梯度信息(PGI)和广义高效层聚合网络(GELAN)与 YOLOv11 的结合,以解决深度网络数据传输时的信息丢失问题。PGI 能为目标任务提供完整输入信息,计算目标函数以更新网络权重。GELAN 作为轻量级网络架构,由 SPPELAN、ELAN1、RepNCSPELAN4 等模块组成。我们将 GELAN 代码集成进 YOLOv11, 实验脚本显示,结合 GELAN 的 YOLOv11 在 MS COCO 数据集目标检测任务中或有良好表现。

魔改工程师的博客 1250

EventLoop再分析之IO线程(29)

EventLoop IO 线程的简单描述 进程(线程)wait/notify pipe socketpair eventfd eventfd 是一个比 pipe 更高效的线程间事件通知机制,一方面它比 pipe 少用一个 file descripor,节省了资源;另一方面,eventfd 的缓冲区管理也简单得多,全部“buffer” 只有定

Riak, Spark, Golang, Erlang, 云存储, 云计算, 数据挖掘 6127

大数据架构中的数据治理:元数据管理与数据血缘追踪实践

本文将聚焦大数据架构中数据治理的两大核心支柱——元数据管理与数据血缘追踪元数据管理的目标、类型与实施步骤(从需求分析到工具落地);数据血缘追踪的技术实现(静态解析、动态捕获、混合方案)与应用场景;如何将两者结合,构建完整的数据治理体系,并通过真实案例展示落地效果。元数据管理:定义了业务/技术/操作元数据,讲解了工具选型(如Apache Atlas)、采集(Hook/API)、存储(关系库+图数据库)、应用(数据发现、质量监控);数据血缘追踪。

欢迎来到我的CSDN空间!这里聚焦AI大模型应用实战,分享前沿技术、实战案例与开发经验。 875

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

muduo网络库net篇:写在进一步阅读之前

socket sockets命名空间封装linux API InetAddress封装sockaddr_in*赋值 Socket封装socket操作 Buffer类 关于Muduo 中输入输出缓冲区的设计与实现的原理,陈硕已经写的很详细了,可参考[Buffer 类的设计][1] 。在这里,我主要关注代码数据方面。 Buffer类成员数据如下: public: static

月寒日暖的博客 339

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

muduo学习笔记:net部分之Channel

正如其名,muduo中Channel是底层通过Socket建立TCP通信的通道,用于事件分发。Channel对fd的事件相关方法进行了封装,例如负责注册fd的可读或可写事件到EvenLoop,又如fd产生事件后要如何响应。 Channel与fd是聚合关系,一个fd对应一个channel,不实际拥有fd,Channel析构是不会close当前fd。文件描述符fd可以是socket、eventfd、timerfd或signalfd。 Channel一般作为其他类的成员,不被直接使用,而使用更上层的封装,例如用于

热爱生活,忠于自己 1042

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

muduo库net源码分析六(Socket 封装)

SocketsOps.h/ SocketsOps.cc 封装了socket相关系统调用(全局函数,位于muduo::net::sockets名称空间中)。 Socket.h/Socket.cc(Socket类) 用RAII方法封装socket file descriptor。 InetAddress.h/InetAddress.cc(InetAddress类) 网际地址sockaddr_in封装 Endian.h 封装了字节序转换函数(全局函数,位于muduo::net::sockets名..

侯彩桦 441

muduo_net库源码分析(25)

TCP网络编程本质     TCP网络编程最本质是的处理三个半事件         连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接         连接断开:主动断开(close、shutdown),被动断开(read返回0)         消息到达:文件描述符可读         消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件;这里的

Riak, Spark, Golang, Erlang, 云存储, 云计算, 数据挖掘 2462

34muduo_net库源码分析(十)

1.连接关闭时序图 2.代码 1.TcpConnection.h // Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that

INGNIGHT的专栏 654

muduo_net库源码分析(一)

1.TCP网络编程本质 TCP网络编程最本质是的处理三个半事件 1.连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接。 2.连接断开:主动断开(close、shutdown),被动断开(read返回0)。 3.消息到达:文件描述符可读。 4.消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件;这里的发送完毕是指数据写入内核缓冲区,将由TCP协议栈负责数据的发送与重传,不代表对端已经接收到数据。 2.EchoServer类图 显然,这是基于对象的编程思想,在Ec

ShenHang_的博客 358

muduo/net库(1)

如果说你不用muduo的net库,让你用epoll监听,你会怎样写服务器? 下面是我写的,为了让代码的逻辑更加清晰,我这里没有进行出错判断。 这只是一个简单的回射服务器 #include <iostream> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #inc...

xiuxiu__deng的博客 264

muduo库net源码分析一(网络编程本质)

TCP网络编程最本质的是处理三个半事件 1、连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接。 2、连接断开:主动断开(close、shutdown),被动断开(read返回0)。 3、消息到达:文件描述符可读。 4、消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件,这里的发送完毕是指数据写入操作系统缓冲区,将由TCP协议栈负责数据的发送与重传,不代表对方已经接收到数据。对于高流量的程序,应用要在发送完毕后再发送,以免数据丢包。 一个套接字有两个缓冲区

侯彩桦 1693

muduo网络库学习之muduo_inspect 库涉及到的类

muduo inspect 库通过HTTP方式为服务器提供监控接口, 现在只实现进程相关信息的监控,通过成员ProcessInspector 实现。 ProcessInspector // 通过ProcessInfo返回进程信息      ProcessInfo // 获取进程相关信息 我们可以参照 ProcessInspector 实现一个如TcpStateInspector,作为

Meditation 3921

29muduo_net库源码分析(五)

1.进程(线程)wait/notify (1)pipe (2)socketpair (3)eventfd,eventfd是一个比 pipe更高效的线程间事件通知机制,一方面它比 pipe 少用一个file descripor,节省了资源;另一方面,eventfd的缓冲区管理也简单得多,全部“buffer”只有定长8 bytes,不像 pipe 那样可能有不定长的真正buffer。 in

INGNIGHT的专栏 512

http实现源码(40-1)

HttpRequest头文件(包含实现) HttpResquest.h // Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that ca

Riak, Spark, Golang, Erlang, 云存储, 云计算, 数据挖掘 3147
上一篇: 多线程与并发服务器设计(23 - 2 )
下一篇: EpollPoller --- muduo_net库源码分析(27)
laohan_
博客等级 码龄15年 112粉丝 224原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值