下面给出一个基于 std::thread/std::mutex/std::condition_variable 的简易线程池实现,它支持:
- 提交任意可调用对象(函数、Lambda、
std::bind……)
- 获取
std::future 以便异步取回结果
- 自动管理线程的启动和销毁
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <future>
#include <condition_variable>
#include <functional>
#include <iostream>
class ThreadPool {
public:
explicit ThreadPool(size_t threadCount);
~ThreadPool();
// 提交任务,返回一个 future 用于获取结果
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::invoke_result<F, Args...>::type>;
private:
// 工作线程
std::vector<std::thread> workers;
// 任务队列
std::queue<std::function<void()>> tasks;
// 同步
std::mutex queueMutex;
std::condition_variable condition;
bool stop = false;
};
// 构造:创建线程并进入工作循环
ThreadPool::ThreadPool(size_t threadCount) {
for (size_t i = 0; i < threadCount; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{ // 获取任务
std::unique_lock<std::mutex> lock(this->queueMutex);
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();
}
});
}
}
// 析构:通知所有线程退出并 join
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
worker.join();
}
// enqueue 实现
template<typename F, typename... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::invoke_result<F, Args...>::type>
{
using ReturnType = typename std::invoke_result<F, Args...>::type;
// 封装任务
auto taskPtr = std::make_shared<std::packaged_task<ReturnType()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<ReturnType> res = taskPtr->get_future();
{
std::unique_lock<std::mutex> lock(queueMutex);
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([taskPtr]{ (*taskPtr)(); });
}
condition.notify_one();
return res;
}
// 使用示例
int main() {
ThreadPool pool(4); // 4 个线程
// 提交任务并获取 future
auto f1 = pool.enqueue([](int a, int b) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
return a + b;
}, 3, 7);
auto f2 = pool.enqueue([] {
std::cout << "Hello from thread " << std::this_thread::get_id() << "\n";
});
// 取回结果
std::cout << "3 + 7 = " << f1.get() << "\n";
f2.get();
return 0;
}
说明:
- 构造函数中启动固定数量的线程,每个线程不断从任务队列拉取并执行任务。
enqueue 用 std::packaged_task 和 std::future 包装提交的任务,使用者可以在任意时刻通过 .get() 拿到返回值或捕获异常。
- 析构时先设置
stop = true,然后 notify_all() 唤醒所有线程,线程看到停止标志并且任务队列空了后就退出循环,最后主线程 join 它们。
优点:
可以根据业务需求进一步扩展:
- 支持任务优先级队列
- 支持动态调整线程数
- 支持超时等待、线程亲和性等等
如有更高级需求,亦可考虑成熟库:
- Boost.Asio(
boost::asio::thread_pool)
- 现代协程库(C++20 coroutines + executor)
- 第三方线程池实现(如 ctpl 等)