首先我们得明白ThreadPool类是干嘛的,就是生成一个线程池。是基于Thread类实现的。
首先我们看ThreadPool的数据成员。代码:
mutable MutexLock mutex_;
Condition notEmpty_ GUARDED_BY(mutex_);
Condition notFull_ GUARDED_BY(mutex_);
string name_;
Task threadInitCallback_;
std::vector<std::unique_ptr<muduo::Thread>> threads_;
std::deque<Task> queue_ GUARDED_BY(mutex_);
size_t maxQueueSize_;
bool running_;
std::vector<std::unique_ptr<muduo::Thread>> threads_; 这个就是线程池的实现,使用vector来存储每个线程的智能指针
string name_; 是线程池的名字,在muduo中默认为ThreadPool
std::deque<Task> queue_ GUARDED_BY(mutex_); 使用双端队列实现的任务队列
mutable MutexLock mutex_;
Condition notEmpty_ GUARDED_BY(mutex_);
Condition notFull_ GUARDED_BY(mutex_); 这个互斥量和条件变量保任务队列的线程安全
size_t maxQueueSize_; 任务队列最多能容纳多少任务
bool running_; 线程池是否运行
知道了数据成员,当然就要看类的构造函数,代码
explicit ThreadPool(const string& nameArg = string("ThreadPool"));
ThreadPool::ThreadPool(const string& nameArg)
: mutex_(),
notEmpty_(mutex_),
notFull_(mutex_),
name_(nameArg),
maxQueueSize_(0),
running_(false)
{
}
没有什么特别的,就是数据的初始化,还没有新建线程池,从ThreadPoo