写一个C++ 线程池
时间: 2023-06-30 17:25:13 浏览: 90
c++ 线程池
4星 · 用户满意度95%
好的,下面是一个简单的 C++ 线程池的实现:
```c++
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class ThreadPool {
public:
ThreadPool(size_t num_threads) {
for (size_t i = 0; i < num_threads; ++i) {
threads_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this] {
return !tasks_.empty() || stop_;
});
if (stop_ && tasks_.empty()) {
return;
}
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mutex_);
stop_ = true;
}
condition_.notify_all();
for (std::thread& thread : threads_) {
thread.join();
}
}
template<typename F, typename... Args>
void enqueue(F&& f, Args&&... args) {
{
std::unique_lock<std::mutex> lock(mutex_);
tasks_.emplace(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
}
condition_.notify_one();
}
private:
std::vector<std::thread> threads_;
std::queue<std::function<void()>> tasks_;
std::mutex mutex_;
std::condition_variable condition_;
bool stop_ = false;
};
int main() {
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.enqueue([](int id) {
std::cout << "Task " << id << " is running." << std::endl;
}, i);
}
return 0;
}
```
这个线程池使用一个队列来存储任务,每个线程都会不停地从队列中取出任务并执行。当队列为空时,线程会等待直到有新的任务加入。当线程池被销毁时,所有线程都会退出。我们可以通过调用 `enqueue` 方法向线程池中添加任务。
阅读全文