#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <memory>
#include <Windows.h>
class ThreadPool {
public:
// 当调用构造函数创建线程池的时候,只会将任务放进tasks集合中,并执行内部的lambda表达式函数体的代码
ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back(
[this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
// 满足this->stop 等于true或者队列不为空时,跳过等待。这个this->stop表示,我的整个线程池都不适用了,不干了,整个程序结束。
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();
}
}
);
}
}
// 这个泛型F对应的参数f,可以看作是任务的函数体
template<class F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace(f);
}
// 一开始是4个线程在等待,唤醒其中一个线程干活
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;
};
int main() {
// 创建4个线程的线程池
ThreadPool pool(4);
for (int i = 0; i < 4; ++i) {
pool.enqueue([i] {
std::cout << "hello from task " << i << std::endl;
Sleep(20000);
});
}
for (int i = 0; i < 10; i++) {
Sleep(1000);
}
pool.enqueue([] {
std::cout << "hello from task " << 5 << std::endl;
Sleep(1000);
});
return 0;
}
C++线程池实现例子
于 2024-01-18 16:40:12 首次发布