写一段最简单的线程池代码
时间: 2023-06-16 21:03:20 浏览: 77
Python 线程池用法简单示例
以下是一个简单的线程池代码示例,其中包括线程池初始化、任务添加、线程执行任务和线程池销毁等功能:
```c++
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
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<class F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<F>(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;
};
```
在上述代码中,构造函数初始化了线程池,并创建了指定数量的线程。enqueue()函数用于向线程池中添加任务。当调用enqueue()时,任务会被放置在任务队列中,并通过std::condition_variable通知线程池中的线程执行任务。线程池的析构函数会等待所有线程完成任务后销毁线程池。
阅读全文