不废话直接贴源码 综合,极简,好用易懂:
ThreadPool.hpp 支持静态类 仿函数 lambda 根据情况自己抄去改
#pragma once
#include <iostream>
#include <stdexcept>
#include <memory>
#include <vector>
#include <queue>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <future>
#include <functional>
class ThreadPool
{
using Task = std::function<void(void)>; //回调函数类型
std::vector<std::thread> workers; //工作线程
std::queue<Task> tasks; //回调函数
std::condition_variable condition; //必须与unique_lock配合使用
std::mutex queMutex;
std::atomic_bool bStop;
const int MAX_THREADS = 1000; //最大线程数目
public:
using Type = enum class _type{ Sync = 0, ASync };
Type eType;
//默认开一个线程 tp=Sync同步方式,=ASync异步方式
ThreadPool(size_t threads = 1, Type tp= Type::Sync) :bStop(false), eType(t