概述
本文所提线程池以c++11为基础,依赖c++11一些新特性,如thread、funciton等特性。线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程,每个线程使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。其组成部分分为以下四块:
- 线程管理器:用于创建并管理线程池
- 工作线程:线程池中线程
- 任务接口:每个人物必须实现的接口,以供工作线程调度任务的执行
- 任务队列:用于存放没有处理的任务,提供一种缓冲机制
部分代码实现
- 入任务队列,并唤醒空闲线程
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
- 出任务队列
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
- 析构函数
condition.notify_all();
for (std::thread &worker : workers)
worker.join();