一个完备的线程池例子
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>class ThreadPool
{
public:explicit ThreadPool(int numThreads) : stop(false){// 创建指定数量的线程,并将它们绑定到 workerFunction 函数if (numThreads < 1) numThreads = 1;for (int i = 0; i < numThreads; i++){workers.emplace_back(&ThreadPool::workerFunction, this);}}template<class F, class... Args>auto enqueue(F&& f, Args&&... args)->std::future<decltype(f(args...))>{using return_type = decltype(f(args...));// 创建一个 packaged_task,将函数和参数绑定起来auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));std::future<return_type> result = task->get_future();{std::unique_lock<std::mutex> lock(queueMutex);if (stop)throw std::runtime_error("Enqueue on stopped Threadpool");tasks.emplace([task] {(*task)(); });}// 通知一个等待中的线程有新任务可执行condition.notify_one();return result;}~ThreadPool(){{std::lock_guard<std::mutex> lock(queueMutex);stop = true;}// 通知所有线程停止并等待它们结束condition.notify_all();for (std::thread& worker : workers)worker.join();}
private:void workerFunction(){while (true){std::function<void()> task;{std::unique_lock<std::mutex> lock(queueMutex);/* 如果线程池被要求停止且任务队列为空,则线程结束调用过程先判断lamda表达式,如果true则继续执行,获取互斥锁资源,false则调用wait方法阻塞线程,释放互斥锁资源条件变量唤醒时,还是先判断lamda表达式,过程同上*/condition.wait(lock, [this] {return stop || !tasks.empty(); });if (stop && tasks.empty())return;// 从队列中取出一个待执行的任务task = std::move(tasks.front());tasks.pop();}task();}}
private:std::vector<std::thread> workers; // 线程池中的线程std::queue<std::function<void()>> tasks; // 任务队列std::mutex queueMutex; // 互斥量,用于保护任务队列std::condition_variable condition; // 条件变量,用于线程等待和唤醒bool stop; // 标志是否停止线程池
};int myFunc(int id)
{std::cout << "Task " << id << " is running." << std::endl;return id * id;
}int main()
{ThreadPool pool(4);// 创建一个线程池,包含 4 个线程// 添加任务到线程池std::vector<std::future<int> > results;for (int i = 0; i < 10; i++){results.push_back(pool.enqueue(&myFunc, i));}// 获取任务的返回值for (auto& result : results){std::cout << "result: " << result.get() << std::endl;}return 0;
}