muduo::ThreadPoll分析

线程池本质上是一个生产者消费者的模型。在线程池有一个存放现场的ptr_vector,相当于消费者;有一个存放任务的deque,相当于仓库。线程(消费者)去仓库取任务,然后执行;当有新程序员是生产者,当有新任务时,就把任务放到deque(仓库)。

任务队列(仓库)是有边界的,所以在实现时需要有两个信号量,相当与BoundedBlockingQueue。

每个线程在第一次运行时都会调用一次回调函数threadInitCallback_,为线程执行做准备。

在线程池开始运行之前,要先设置任务队列的大小(即调用setMaxQueueSize),因为运行线程池时,线程会从任务队列取任务。

逻辑清楚了,后面分析源代码就容易了。

ThreadPoll.h

class ThreadPool : boost::noncopyable
{
 public:
  typedef boost::function<void ()> Task;//函数对象,相当与任务

  explicit ThreadPool(const string& nameArg = string("ThreadPool"));
  ~ThreadPool();

  // Must be called before start().因为在start()调用时,会从队列取任务
  void setMaxQueueSize(int maxSize) { maxQueueSize_ = maxSize; }//设置任务队列的大小,必须在start之前设置。
  void setThreadInitCallback(const Task& cb)//设置回调函数,每次在执行任务前先调用回调函数
  { threadInitCallback_ = cb; }

  void start(int numThreads);//设置线程池的大小
  void stop();//停止线程池

  const string& name() const
  { return name_; }

  size_t queueSize() const;

  // Could block if maxQueueSize > 0
  void run(const Task& f);//把任务添加到任务队列,可能不是立即执行。
#ifdef __GXX_EXPERIMENTAL_CXX0X__
  void run(Task&& f);
#endif

 private:
  bool isFull() const;
  void runInThread();//真正执行任务的函数
  Task take();//从任务队列去任务

  mutable MutexLock mutex_;
  Condition notEmpty_;//任务队列非空信号量
  Condition notFull_;//任务队列非满信号了
  string name_;
  Task threadInitCallback_;//回调函数,在线程池第一次执行任务是调用。
  boost::ptr_vector<muduo::Thread> threads_;//存放线程
  std::deque<Task> queue_;//存放任务
  size_t maxQueueSize_;
  bool running_;//线程池是否运行
};

ThreadPoll.cc

ThreadPool::ThreadPool(const string& nameArg)
  : mutex_(),
    notEmpty_(mutex_),
    notFull_(mutex_),
    name_(nameArg),
    maxQueueSize_(0),
    running_(false)
{
}

ThreadPool::~ThreadPool()
{
  if (running_)//如果线程池开始运行
  {
    stop();
  }
}

void ThreadPool::start(int numThreads)//线程池中的线程数,并开始运行线程池
{
  assert(threads_.empty());
  running_ = true;
  threads_.reserve(numThreads);
  for (int i = 0; i < numThreads; ++i)
  {
    char id[32];
    snprintf(id, sizeof id, "%d", i+1);
    threads_.push_back(new muduo::Thread(
          boost::bind(&ThreadPool::runInThread, this), name_+id));//绑定runInThread为线程运行函数
    threads_[i].start();//线程开始执行
  }
  if (numThreads == 0 && threadInitCallback_)//如果线程池为空,且有回调函数,则调用回调函数。这时相当与只有一个主线程
  {
    threadInitCallback_();
  }
}

void ThreadPool::stop()
{
  {
  MutexLockGuard lock(mutex_);
  running_ = false;
  notEmpty_.notifyAll();//通知所有等待在任务队列上的线程
  }
  for_each(threads_.begin(),
           threads_.end(),
           boost::bind(&muduo::Thread::join, _1));//每个线程都调用join
}

size_t ThreadPool::queueSize() const
{
  MutexLockGuard lock(mutex_);
  return queue_.size();
}

void ThreadPool::run(const Task& task)//向任务对了添加任务
{
  if (threads_.empty())//如果线程池是空的,那么直接由当前线程执行任务
  {
    task();
  }
  else
  {
    MutexLockGuard lock(mutex_);
    while (isFull())//当任务对了已满
    {
      notFull_.wait();//等待非满通知
    }
    assert(!isFull());

    queue_.push_back(task);//添加到任务队列
    notEmpty_.notify();//告知任务对了已经非空,可以执行了
  }
}

#ifdef __GXX_EXPERIMENTAL_CXX0X__
void ThreadPool::run(Task&& task)
{
  if (threads_.empty())
  {
    task();
  }
  else
  {
    MutexLockGuard lock(mutex_);
    while (isFull())
    {
      notFull_.wait();
    }
    assert(!isFull());

    queue_.push_back(std::move(task));
    notEmpty_.notify();
  }
}
#endif

ThreadPool::Task ThreadPool::take()//从队列取出任务
{
  MutexLockGuard lock(mutex_);
  // always use a while-loop, due to spurious wakeup
  while (queue_.empty() && running_)//如果队列已空,且线程已经开始运行
  {
    notEmpty_.wait();//等待队列非空信号
  }
  Task task;
  if (!queue_.empty())
  {
    task = queue_.front();//取出队列头的任务
    queue_.pop_front();
    if (maxQueueSize_ > 0)
    {
      notFull_.notify();//通知,告知任务队列已经非满了,可以放任务进来了
    }
  }
  return task;
}

bool ThreadPool::isFull() const//判断队列是否已满
{
  mutex_.assertLocked();//是否被当前线程锁住
  return maxQueueSize_ > 0 && queue_.size() >= maxQueueSize_;
}

void ThreadPool::runInThread()
{
  try
  {
    if (threadInitCallback_)//如果有回调函数,先调用回调函数。为任务执行做准备
    {
      threadInitCallback_();
    }
    while (running_)//线程池已经开始运行
    {
      Task task(take());//取出任务。有可能阻塞在这里,因为任务队列为空。
      if (task)
      {
        task();//执行任务
      }
    }
  }
  catch (const Exception& ex)
  {
    fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str());
    fprintf(stderr, "reason: %s\n", ex.what());
    fprintf(stderr, "stack trace: %s\n", ex.stackTrace());
    abort();
  }
  catch (const std::exception& ex)
  {
    fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str());
    fprintf(stderr, "reason: %s\n", ex.what());
    abort();
  }
  catch (...)
  {
    fprintf(stderr, "unknown exception caught in ThreadPool %s\n", name_.c_str());
    throw; // rethrow
  }
}

写个测试函数:

//threadpoolTest.cpp

#include <muduo/base/ThreadPool.h>
#include <muduo/base/CurrentThread.h>

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

using namespace muduo;

class TaskClass
{
public:
    TaskClass(int id):id_(id){}
    void Print()
    {
        std::cout<<"Task ID is: "<<id_<<", Thread ID is: "<<CurrentThread::tid()<<", Thread name is: "<<CurrentThread::name()<<std::endl;
    }
private:
    int id_;

};

void ThreadInitFunc()
{
    std::cout<<"Init Thread. "<<", Thread ID is: "<<CurrentThread::tid()<<", Thread name is: "<<CurrentThread::name()<<std::endl;
}

int main()
{
    ThreadPool pool;
    pool.setMaxQueueSize(20);
    pool.setMaxQueueSize(20);
    pool.setThreadInitCallback(boost::bind(ThreadInitFunc));
    pool.start(4);

    for(int i=0; i<20; ++i)
    {
        boost::shared_ptr<TaskClass> taskClass(new TaskClass(i));
        pool.run(boost::bind(&TaskClass::Print, taskClass));
    }
    sleep(3);
    pool.stop();

    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-28 06:33:35

muduo::ThreadPoll分析的相关文章

muduo::TcpConnection分析

TcpConnection是使用shared_ptr来管理的类,因为它的生命周期模糊.TcpConnection表示已经建立或正在建立的连接,状态只有kConnecting.kConnected.kDisconnected.kDisconnecting,它初始化时,构造函数的sockfd表示正在建立连接kConnecting. 建立连接后,用户只需处理收发数据,发送数据它会自动处理,收取数据后,会调用用户设置的MessageCallback函数来处理收到的数据. TcpConnection中封装

muduo::EventLoop分析

EventLoop是整个Reactor的核心.其类图如下: one loop per thread意味着每个线程只能有一个EventLoop对象,用变量 __thread EventLoop* t_loopInThisThread = 0; 表示,在创建EventLoop对象时将t_loopInThisThread赋值,以后再创建时就可以检查这个变量,如果已经赋值就说明当前线程已经创建过EventLoop对象了.线程调用静态函数EventLoop::getEventLoopOfCurrentTh

muduo源代码分析--Reactor模式在muduo中的使用

一. Reactor模式简单介绍 Reactor释义"反应堆",是一种事件驱动机制.和普通函数调用的不同之处在于:应用程序不是主动的调用某个API完毕处理.而是恰恰相反.Reactor逆置了事件处理流程,应用程序须要提供对应的接口并注冊到Reactor上,假设对应的时间发生,Reactor将主动调用应用程序注冊的接口,这些接口又称为"回调函数". 二. moduo库Reactor模式的实现 muduo主要通过3个类来实现Reactor模式:EventLoop,Cha

muduo源代码分析--Reactor在模型muduo使用(两)

一. TcpServer分类: 管理所有的TCP客户连接,TcpServer对于用户直接使用,直接控制由用户生活. 用户只需要设置相应的回调函数(消息处理messageCallback)然后TcpServer::start()就可以. 主要数据成员: boost::scoped_ptr<Accepter> acceptor_; 用来接受连接 std::map<string,TcpConnectionPtr> connections_; 用来存储全部连接 connectonCallb

muduo网络库预备知识点

TCP网络编程的三个半事件 非阻塞网络编程中应用层要使用缓冲区 发送方应用层为什么使用缓冲区 接收方应用层方为什么使用缓冲 如何设计使用缓冲区 什么是Reactor模式 non-blocking IO IO multiplexing muduo推荐的模式 线程池大小的阻抗匹配原则 Eventloop采用level trigger的原因 前面都在分析muduo/base中的源码,这些是辅助网络库的.在分析网络库前,先总结一下相关知识点. TCP网络编程要关注哪些问题?muduo网络库总结为三个半事

Muduo网络库源码分析(一) EventLoop事件循环(Poller和Channel)

从这一篇博文起,我们开始剖析Muduo网络库的源码,主要结合<Linux多线程服务端编程>和网上的一些学习资料! (一)TCP网络编程的本质:三个半事件 1. 连接的建立,包括服务端接受(accept) 新连接和客户端成功发起(connect) 连接.TCP 连接一旦建立,客户端和服务端是平等的,可以各自收发数据. 2. 连接的断开,包括主动断开(close 或shutdown) 和被动断开(read(2) 返回0). 3. 消息到达,文件描述符可读.这是最为重要的一个事件,对它的处理方式决定

muduo源码分析--我对muduo的理解

分为几个模块 EventLoop.TcpServer.Acceptor.TcpConnection.Channel等 对于EventLoop来说: 他只关注里面的主驱动力,EventLoop中只关注poll,这类系统调用使得其成为Reactor模式,EventLoop中有属于这个loop的所有Channel,这个loop属于哪一个Server. 几个类存在的意义: 从应用层使用的角度来看,用户需要初始化一个EventLoop,然后初始化一个TcpServer(当然也可以自定义个TcpServer

muduo::Logging、LogStream分析

Logging LogStream Logging Logging类是用来记录分析日志用的. 下面是Logging.h的源码 namespace muduo { class TimeZone;//forward declaration class Logger { public: enum LogLevel//用来设置不同的日志级别 { TRACE, DEBUG, INFO, WARN, ERROR, FATAL, NUM_LOG_LEVELS,//级别个数 }; // compile time

Muduo网络库源码分析(四)EventLoopThread和EventLoopThreadPool的封装

muduo的并发模型为one loop per thread+ threadpool.为了方便使用,muduo封装了EventLoop和Thread为EventLoopThread,为了方便使用线程池,又把EventLoopThread封装为EventLoopThreadPool.所以这篇博文并没有涉及到新鲜的技术,但是也有一些封装和逻辑方面的注意点需要我们去分析和理解. EventLoopThread 任何一个线程,只要创建并运行了EventLoop,就是一个IO线程. EventLoopTh