C++实现简易线程池

本线程池是定量线程池,无法动态扩容/减少。

线程池讲解:

实现线程池记住5个成员变量即可:
1、std::vectorstd::thread workers 作为线程池,构造函数内部给他push_back定量的线程,并设置回调。
2、std::queue<std::function<void()>> tasks 作为任务队列,客户端传入函数对象即可。
3、std::mutex queueMutex; 保证对任务队列的存取线程安全
4、std::condition_variable condition;配合锁使用,让线程睡眠,且设置了条件自动唤醒,是重点。
5、std::atomic stop; 当线程池析构后,stop==true,线程就会一直自动醒来,直到处理完所有任务,再关闭。

#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <atomic>


class ThreadPool {
public:
    ThreadPool(int numThreads): stop(false) {
        for (int i = 0; i < numThreads; ++i) {
            workers.push_back(std::thread([this](){
                while (1) {
                    std::function<void()> task;
                    {
                        std::unique_lock lock(queueMutex);
                        /* 满足条件自动醒,收到notify强制醒
                           当收到stop后,就会一直自动醒,直到把所有的task处理完,关闭线程
                        */
                        condition.wait(lock, [&](){ return stop || !tasks.empty(); }); 
                        if (stop && tasks.empty()) {
                            std::cout << "Thread " << std::this_thread::get_id() << " has finished." << std::endl;
                            return;
                        }
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            }));
        }
    }

    ~ThreadPool() {
        stop = true;
        condition.notify_all(); //唤醒所有线程,逐个获得锁进行if (stop && tasks.empty())判断
        for (std::thread &worker : workers) {
            worker.join();
        }
    }

    void enqueue(std::function<void()> task) {
        std::unique_lock lock(queueMutex);
        tasks.push(std::move(task));
        condition.notify_one();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queueMutex;
    std::condition_variable condition;
    std::atomic<bool> stop;
};

使用示例:

#include "1.h"

void exampleTask(int id) {
    std::cout << "Task " << id << " is being processed by thread " << std::this_thread::get_id() << std::endl;
}

int main() {
    ThreadPool pool(3);  // 创建包含3个线程的线程池

    for (int i = 0; i < 10; ++i) {
        pool.enqueue([i](){ //传入一个任务
            exampleTask(i);
        });
    }
}

结果如图:
在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值