ThreadPool.h
class ThreadPool
{
/* key member*/
private:
/*condition variables */
Condition notEmpty_;
Condition notFull_;
/* thread pool*/
boost::ptr_vector<muduo::Thread> threads_;
/* task pool*/
std::deque<Task> queue_;
/*key member function*/
public:
void start(int numThreads);
void run(const Task& f);
private:
void runInThread();
Task take();
};
简单解析
1.threads_ 是线程池,由 start 函数生成numThreads个线程。此时,由于任务队列queue_中为空,所有线程阻塞。
2.run 函数并非直接调用线程执行任务f,而是将f存入queue_中并通过notEmpty尝试唤醒一个线程,
queue_满了时,通过notFull阻塞
3.runInThread 是线程执行的函数主体,包含一个while循环,不断通过take函数在queue_中获取task并且执行
4. 线程池是一个典型的生产者-消费者模型
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论