1.线程池结
2.成员变量
- cond_:通知线程队列中的线程来取任务
- threads_:线程队列,里面存放的是muduo::Thread
- queue_:任务队列
- running_:此线程池是否工作
muduo新版中添加了一些变量,但实现的基本功能没变
3.测试用例 ThreadPool_test.cc
以muduo-0.9.1版本为例:
#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)));
}
muduo::CountDownLatch latch(1);
pool.run(boost::bind(&muduo::CountDownLatch::countDown, &latch));
latch.wait();
pool.stop();
}
muduo::ThreadPool pool(“MainThreadPool”);
pool.start(5);
- 首先创建了一个线程池,并创建出了5个工作线程,每个工作线程函数是 runInThread,如下图所示。
- 接着调用 start()函数,创建线程,接下来的流程参考 6.测试用例 Thread_test.cc
- 线程函数 runInThread定义如下:
- 其中 take()函数定义如下:
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)));
}
- 向任务队列中添加 2个print()任务,100个printString()任务
- run()函数定义如下:
muduo::CountDownLatch latch(1);
pool.run(boost::bind(&muduo::CountDownLatch::countDown, &latch));
latch.wait();
- 向任务队列中添加 CountDownLatch()任务,当工作线程执行完此任务时,latch.wait()解除阻塞。CountDownLatch()定义
pool.stop();
- 线程池停止工作。
- 由于此时running_ = false,所以线程函数 runInThread会跳出while循环,线程函数结束。
- 注:muduo新版中添加了多个测试用例,总体实现一样。
- 运行部分结果:
参考代码