c++ thread 线程池代码
时间: 2023-07-07 22:42:16 浏览: 81
线程池代码
以下是一个简单的 C++ 线程池实现代码,使用了 C++11 中的 `<thread>` 和 `<queue>` 库:
```cpp
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
for (;;) {
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 <typename Function>
void enqueue(Function&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<Function>(f));
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker: workers) {
worker.join();
}
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop = false;
};
```
使用方式:
```cpp
ThreadPool pool(4); // 创建一个具有 4 个线程的线程池
pool.enqueue([] {
// 执行任务 1
});
pool.enqueue([] {
// 执行任务 2
});
// 等待所有任务完成
```
阅读全文