目录
一、背景
线程池是一种管理和复用线程资源的设计方法,旨在提高程序的并发性能和资源利用效率。它的基本原理是通过预先创建一定数量的线程,并将这些线程放入一个“池”中,当有任务需要执行时,从池中取出空闲线程来执行任务,任务完成后,线程回到池中等待下一个任务。
二、实现方式
- 任务队列: 线程池需要维护一个任务队列,任务队列用于存储等待执行的任务。
- 工作线程: 线程池包含多个工作线程,工作线程从任务队列中取出任务并执行。
- 同步机制: 为了保证线程安全,任务队列的访问需要使用同步机制,如互斥锁和条件变量。
三、注意事项
- 线程安全: 任务队列的访问需要使用同步机制来保证线程安全。
- 任务调度: 需要有效的任务调度机制来管理任务的添加和线程的唤醒。
- 资源销毁: 在线程池销毁时,需要确保所有线程都能正确退出并释放资源。
- 异常处理: 要考虑任务执行过程中可能发生的异常,并进行适当的处理。
四、代码示例
下面是一个简单的C++线程池实现示例:
#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
class ThreadPool {
public:
ThreadPool(size_t threads);
~ThreadPool();
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;
private:
// 线程工作函数
void worker();
// 线程池线程
std::vector<std::thread> workers;
// 任务队列
std::queue<std::function<void()>> tasks;
// 同步
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for (size_t i = 0; i < threads; ++i)
workers.emplace_back([this] { this->worker(); });
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
worker.join();
}
void ThreadPool::worker()
{
while (true)
{
std::function<void()> task;
{
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();
}
task();
}
}
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
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();
return res;
}
int main()
{
ThreadPool pool(4);
auto result1 = pool.enqueue([](int a, int b) { return a + b; }, 1, 2);
auto result2 = pool.enqueue([](int a, int b) { return a * b; }, 3, 4);
std::cout << "1 + 2 = " << result1.get() << std::endl;
std::cout << "3 * 4 = " << result2.get() << std::endl;
return 0;
}
代码说明:
1. ThreadPool类构造函数创建指定数量的线程,并启动它们。
2. 每个线程运行worker函数,该函数从任务队列中取出任务并执行。
3. enqueue函数用于向线程池中添加任务,并返回一个std::future对象,以便获取任务的结果。
4. main函数演示了如何使用线程池来执行两个简单的任务。