线程池


#include <iostream>
#include <thread>
#include <queue>
#include <vector>
#include <mutex>

#include <condition_variable>

using namespace std;
using callback = void(*)(void*);


/// @brief 任务类型
class Task{
public:
    /// @brief  执行函数
    callback  func;

    /// @brief 执行函数参数
    void * args;


    Task(callback f_, void* args_) {
        func = f_;
        args = args_;
    }
};


/// @brief 线程池
class ThreadPool {
public:
    ThreadPool(int threadNums_ = 10, int taskNums_ = 100) : isStop(false) {
        for (int i = 0; i < threadNums_; i++) {
            threads.push_back(new thread(worker, this));
        }


        taskNums = tasknums_;

    }

    ~ThreadPool() {
        isStop = true;

        for (auto &th : threads) {
            if (th.joinable()) {
                th.join();
            }
        }
    }

    /// @brief  线程执行函数
    /// @return 
    static void worker(void *args) {
        ThreadPool* pool = static_cast<ThreadPool* >(args);
        while(true) {
            if (isStop) {
                return;
            }
    
            unique_lock<mutex> lk(pool->mutexPool);
            while(pool->tasks.empty() && pool->isStop == false) {
                pool->cond.wait(lk)
            }

            Task t = pool->tasks.front();
            pool->tasks.pop();

            lk.unlock();

            t->func(t->args);


        }
    }

    bool addTask(Task t) {
        if (tasks.size() == taskNums || isStop) {
            return false;
        }

        {
            unique_lock<mutex> lk(pool->mutexPool);
            tasks.push(t);

            cond.notify_all();
        }

        return true;
    }


private:

    /// @brief  终止信号
    bool isStop;

    /// @brief 线程数
    int taskNums;

    /// @brief 任务队列
    queue<Task> tasks;

    /// @brief 线程数组
    vector<thread> threads;

    /// @brief 线程池锁
    mutex mutexPool;

    /// @brief 条件变量
    condition_variable cond;

};

资料:
https://blog.csdn.net/weixin_45144862/article/details/126914327

https://mp.weixin.qq.com/s?__biz=MzA3NzI1Njk1MQ==&mid=2648577488&idx=1&sn=8889e18fbe87f0a0dc4077c77f096098&chksm=877e7448b009fd5efa860edc0a94550df6a08dfb2cb3206ae3ef32f5ff244bde41b7df3b595c&scene=27

posted @ 2023-09-21 17:41  小海哥哥de  阅读(3)  评论(0编辑  收藏  举报