ThreadPool(16)


threadPool类图

-----------------------

-mutex_:MutexLock  //互斥量 ---> mutexlock--->mutexlockGuard
-cond_:Codition //条件变量
-name:string    //名字
-threads_:boost::ptr_vector<muduo::Thread> //线程池容量
-queue_: std::deque<Task>    //任务队列,任务我们把他作为“函数”
-running_ :bool        // 线程池是否运行
-----------------------------
<<create>>-ThreadPool(name:string)
<<destroy>>-ThreadPool()
+start(numThreads:int):void// 启动线程池
+stop():void            //关闭线程池
+run(f:Task):void //    启动
+runInThread():void //线程池中的线程的回调函数
+take():Task         // 获取任务

--------------------------------------------------


ThreadPool头文件



// 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)

#ifndef MUDUO_BASE_THREADPOOL_H
#define MUDUO_BASE_THREADPOOL_H

#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>


#include <muduo/base/Thread.h>
#include <muduo/base/Types.h>

#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

#include <deque>

namespace muduo
{

class ThreadPool : boost::noncopyable //不可复制
{
 public:
  typedef boost::function<void ()> Task;

  explicit ThreadPool(const string& name = string());
  ~ThreadPool();

  void start(int numThreads);
  void stop();

  void run(const Task& f);

 private:
  void runInThread();
  Task take();

  MutexLock mutex_;
  Condition cond_;
  string name_;
  boost::ptr_vector<muduo::Thread> threads_;
  std::deque<Task> queue_; //线程池的任务队列
  bool running_;//线程池是否处于启动状态
};

}

#endif


ThreadPool的源文件


// 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/ThreadPool.h>

#include <muduo/base/Exception.h>

#include <boost/bind.hpp>
#include <assert.h>
#include <stdio.h>

using namespace muduo;

ThreadPool::ThreadPool(const string& name)
  : mutex_(), //初始化互斥量
    cond_(mutex_), //互斥量跟条件变量进行绑定
    name_(name),
    running_(false)
{
}
//线程池的虚构
ThreadPool::~ThreadPool()
{
    //如果线程池处于运行状态,关闭线程池里的线程
  if (running_)
  {
    stop();
  }
}
//1----->>启动线程池
void ThreadPool::start(int numThreads)
{
    //断言线程池是否为空
  assert(threads_.empty());
  //启动线程池
  running_ = true;
  //开辟numThreads个容量的线程池
  threads_.reserve(numThreads);
  //生产线程,这些线程可以说就是“消费者”
  for (int i = 0; i < numThreads; ++i)
  {
    char id[32];
    snprintf(id, sizeof id, "%d", i);
    threads_.push_back(new muduo::Thread(
        //线程池里的线程的回调函数  runInThread
          boost::bind(&ThreadPool::runInThread, this), name_+id));
    //启动线程
    threads_[i].start();
  }
}

/**
停止线程池里的线程
***/
void ThreadPool::stop()
{
  {
      //加锁
  MutexLockGuard lock(mutex_);
  running_ = false;
    //唤醒线程
  cond_.notifyAll(); 
  }
  //把线程加入退出队列
  for_each(threads_.begin(),
           threads_.end(),
           boost::bind(&muduo::Thread::join, _1));
}
//4---->>> 启动线程池
void ThreadPool::run(const Task& task)
{
    //如果线程池没有线程,那么直接执行任务,也就是说假设没有消费者,那么生产者直接消费产品.
    //而不把任务加入任务队列
  if (threads_.empty())
  {
    task();
  }
  //如果线程池有线程
  else
  {
      //加锁
    MutexLockGuard lock(mutex_);
        //加入任务队列
    queue_.push_back(task);
    //唤醒
    cond_.notify();
  }
}
//3----->>> 这是一个任务分配函数,线程池函数或者线程池里面的函数都可以到这里取出一个任务,然后在自己的线程中执行这和任务,返回一个任务指针
ThreadPool::Task ThreadPool::take()
{
  MutexLockGuard lock(mutex_);
  // always use a while-loop, due to spurious wakeup
  //防止假唤醒,running_ 用来接收线程池发送的“线程退出”命令
  while (queue_.empty() && running_)
  {
    cond_.wait();
  }
  Task task;
  if(!queue_.empty())
  {
    task = queue_.front();
    queue_.pop_front();
  }
  return task;
}

//2---->>线程池(可以把他当做主线程进行理解)里的线程的回调函数,可以在线程池函数中执行一些任务,并不是说只有线程池里面的函数才能执行任务,这能达到负载均衡的效果
void ThreadPool::runInThread()
{
  try
  {
        //测试线程池是否在运行 ,不运行马上停止线程池
    while (running_)
    {
      Task task(take()); //任务是函数,task == 函数指针
      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
  }
}


ThreadPool的测试程序


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

#include <boost/bind.hpp>
#include <stdio.h>

void print()
{
  printf("tid=%d\n", muduo::CurrentThread::tid());
}

void printString(const std::string& str)
{
  printf("tid=%d, str=%s\n", muduo::CurrentThread::tid(), str.c_str());
}

int main()
{
  muduo::ThreadPool pool("MainThreadPool");
  pool.start(5);

  pool.run(print);
  pool.run(print);
  for (int i = 0; i < 100; ++i)
  {
    char buf[32];
    snprintf(buf, sizeof buf, "task %d", i);
    pool.run(boost::bind(printString, std::string(buf)));
  }
 //CountDowndLatch 作文任务放进去,子线会执行,然后唤醒pool,pool就会调用stop停止线程池
  muduo::CountDownLatch latch(1);
  pool.run(boost::bind(&muduo::CountDownLatch::countDown, &latch));
  latch.wait();
  pool.stop();
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值