基于c++的高并发的线程池

学习于大丙老师的教学

线程池包含五个文件:

main.cpp

TaskqQueue.h

TaskQueue.cpp

ThreadPool.cpp

ThreadPool.h

//main.cpp
#include <cstdio>
#include"ThreadPool.h"
#include<iostream>
#include<string.h>
#include<unistd.h>
void taskFunc(void* arg)
{
    int num = *(int*)arg;
    std::cout<<"thread "<<pthread_self() <<"is working, number = "<<num;
    sleep(1);
}

int main()
{
    // 创建线程池
    ThreadPool pool (3, 10);
    for (int i = 0; i < 100; ++i)
    {
        int* num =new int(i+100);
       
        pool.addTask(Task(taskFunc,num));
    }

    sleep(30);
    return 0;
}
//TaskQueue.h
#pragma once

#include<queue>
#include<pthread.h>
using callback = void(*)(void* );
//任务结构体
struct Task//构造函数
{
	Task()
	{
		function = nullptr;
		arg = nullptr;
	}
	Task(callback f, void* arg)
	{
		function = f;
		this->arg = arg;
	}
	callback function;
	void* arg;
};
class TaskQueue
{
public:
    TaskQueue();
    ~TaskQueue();

    // 添加任务
    void addTask(Task& task);

    // 取出一个任务
    Task takeTask();

    // 获取当前队列中任务个数
    inline int taskNumber()
    {
        return m_taskQ.size();
    }

private:
    pthread_mutex_t m_mutex;    // 互斥锁
    std::queue<Task> m_taskQ;   // 任务队列
};


//TaskQueue.cpp
#include "TaskQueue.h"

TaskQueue::TaskQueue()
{
	pthread_mutex_init(&m_mutex,NULL);//锁初始化


}

TaskQueue::~TaskQueue()
{

	pthread_mutex_destroy(&m_mutex);//锁销毁
}

void TaskQueue::addTask(Task & task)//添加任务
{
	pthread_mutex_lock(&m_mutex);//解锁
	this->m_taskQ.push(task);//添加任务
	pthread_mutex_unlock(&m_mutex);//加锁
}


Task TaskQueue::takeTask()//取出任务
{
	pthread_mutex_lock(&m_mutex);
	if (this->m_taskQ.empty() == true)
	{
		return;
	}
	Task t;
	t = this->m_taskQ.front();//取出
	this->m_taskQ.pop();//删除

	pthread_mutex_unlock(&m_mutex);
	return t;
}
//ThreadPool.h
#pragma once
#include"TaskQueue.h"

class ThreadPool//创建线程池对象包含任务队列的头文件
{

public:
    // 创建线程池并初始化
    ThreadPool(int min, int max);
    // 销毁线程池
    ~ThreadPool();
   

    // 给线程池添加任务
    void addTask( Task task);

    // 获取线程池中工作的线程的个数
    int getBusyNum();

    // 获取线程池中活着的线程的个数
    int getAliveNum();


private:
    //
    // 工作的线程(消费者线程)任务函数
    static void* worker(void* arg);
    // 管理者线程任务函数
    static void* manager(void* arg);
    // 单个线程退出
    void threadExit();

private:
    // 任务队列
    TaskQueue* taskQ;

    pthread_t managerID;    // 管理者线程ID因为只有一个不需要指针
    pthread_t* threadIDs;   // 工作的线程ID有多个需要指针
    int minNum;             // 最小线程数量
    int maxNum;             // 最大线程数量
    int busyNum;            // 忙的线程的个数
    int liveNum;            // 存活的线程的个数
    int exitNum;            // 要销毁的线程个数
    pthread_mutex_t mutexPool;  // 锁整个的线程池
    pthread_mutex_t mutexBusy;  // 锁busyNum变量
    pthread_cond_t notFull;     // 任务队列是不是满了
    pthread_cond_t notEmpty;    // 任务队列是不是空了

    bool shutdown;           // 是不是要销毁线程池, 销毁为1, 不销毁为0

};



//ThreadPool.cpp
#include "ThreadPool.h"
#include<iostream>
#include<string.h>
#include<unistd.h>

using namespace std;
ThreadPool::ThreadPool(int minNum, int maxNum)
{
    // 实例化任务队列
    taskQ = new TaskQueue;
    do {
        // 初始化线程池
        minNum = minNum;
        maxNum = maxNum;
        busyNum = 0;
        liveNum = minNum;

        // 根据线程的最大上限给线程数组分配内存
        threadIDs = new pthread_t[maxNum];//max类似于capacity
        if (threadIDs == nullptr)
        {
            cout << "malloc thread_t[] 失败...." << endl;;
            break;
        }
        // 初始化
        memset(threadIDs, 0, sizeof(pthread_t) * maxNum);
        // 初始化互斥锁,条件变量
        if (pthread_mutex_init(&mutexPool, NULL) != 0 ||
            pthread_cond_init(&notEmpty, NULL) != 0)
        {
            cout << "init mutex or condition fail..." << endl;
            break;
        }

        /// 创建线程 //
        // 根据最小线程个数, 创建线程
        for (int i = 0; i < minNum; ++i)
        {
            pthread_create(&threadIDs[i], NULL, worker, this);//threadIDs为子线程执行work函数
            cout << "创建子线程, ID: " << to_string(threadIDs[i]) << endl;
        }
        // 创建管理者线程, 1个
        pthread_create(&managerID, NULL, manager, this);//管理者线程执行manager函数
    } while (0);
}

ThreadPool::~ThreadPool()
{
    shutdown = 1;
    // 销毁管理者线程
    pthread_join(managerID, NULL);
    // 唤醒所有消费者线程
    for (int i = 0; i < liveNum; ++i)
    {
        pthread_cond_signal(&notEmpty);
    }

    if (taskQ) delete taskQ;
    if (threadIDs) delete[]threadIDs;
    pthread_mutex_destroy(&mutexPool);
    pthread_cond_destroy(&notEmpty);
}

void ThreadPool::addTask(Task task)
{
    if (shutdown)
    {
        return;
    }
    // 添加任务,不需要加锁,任务队列中有锁
    taskQ->addTask(task);
    // 唤醒工作的线程
    pthread_cond_signal(&notEmpty);
}

int ThreadPool::getAliveNum()
{
    int threadNum = 0;
    pthread_mutex_lock(&mutexPool);
    threadNum = liveNum;
    pthread_mutex_unlock(&mutexPool);
    return threadNum;
}

int ThreadPool::getBusyNum()
{
    int busyNum1 = 0;
    pthread_mutex_lock(&mutexPool);
    busyNum1 = busyNum;
    pthread_mutex_unlock(&mutexPool);
    return busyNum;
}


// 工作线程任务函数
void* ThreadPool::worker(void* arg)
{
    ThreadPool* pool = static_cast<ThreadPool*>(arg);
    // 一直不停的工作
    while (true)
    {
        // 访问任务队列(共享资源)加锁
        pthread_mutex_lock(&pool->mutexPool);
        // 判断任务队列是否为空, 如果为空工作线程阻塞
        while (pool->taskQ->taskNumber() == 0 && !pool->shutdown)
        {
            cout << "thread " << to_string(pthread_self()) << " waiting..." << endl;
            // 阻塞线程
            pthread_cond_wait(&pool->notEmpty, &pool->mutexPool);

            // 解除阻塞之后, 判断是否要销毁线程
            if (pool->exitNum > 0)//存在的线程是否大于0
            {
                pool->exitNum--;
                if (pool->liveNum > pool->minNum)//活着的线程大于最小线程的数量
                {
                    pool->liveNum--;
                    pthread_mutex_unlock(&pool->mutexPool);
                    pool->threadExit();
                }
            }
        }
        // 判断线程池是否被关闭了
        if (pool->shutdown)
        {
            pthread_mutex_unlock(&pool->mutexPool);
            pool->threadExit();
        }

        // 从任务队列中取出一个任务
        Task task = pool->taskQ->takeTask();
        // 工作的线程+1
        pool->busyNum++;
        // 线程池解锁
        pthread_mutex_unlock(&pool->mutexPool);
        // 执行任务
        cout << "thread " << to_string(pthread_self()) << " start working..." << endl;
        task.function(task.arg);
        delete task.arg;
        task.arg = nullptr;

        // 任务处理结束
        cout << "thread " << to_string(pthread_self()) << " end working...";
        pthread_mutex_lock(&pool->mutexPool);
        pool->busyNum--;
        pthread_mutex_unlock(&pool->mutexPool);
    }

    return nullptr;
}


// 管理者线程任务函数
void* ThreadPool::manager(void* arg)
{
    ThreadPool* pool = static_cast<ThreadPool*>(arg);
    // 如果线程池没有关闭, 就一直检测
    while (!pool->shutdown)
    {
        // 每隔5s检测一次
        sleep(5);
        // 取出线程池中的任务数和线程数量
        //  取出工作的线程池数量
        pthread_mutex_lock(&pool->mutexPool);
        int queueSize = pool->taskQ->taskNumber();
        int liveNum = pool->liveNum;
        int busyNum = pool->busyNum;
        pthread_mutex_unlock(&pool->mutexPool);

        // 创建线程
        const int NUMBER = 2;
        // 当前任务个数>存活的线程数 && 存活的线程数<最大线程个数
        if (queueSize > liveNum && liveNum < pool->maxNum)
        {
            // 线程池加锁
            pthread_mutex_lock(&pool->mutexPool);
            int num = 0;
            for (int i = 0; i < pool->maxNum && num < NUMBER
                && pool->liveNum < pool->maxNum; ++i)
            {
                if (pool->threadIDs[i] == 0)
                {
                    pthread_create(&pool->threadIDs[i], NULL, worker, pool);
                    num++;
                    pool->liveNum++;
                }
            }
            pthread_mutex_unlock(&pool->mutexPool);
        }

        // 销毁多余的线程
        // 忙线程*2 < 存活的线程数目 && 存活的线程数 > 最小线程数量
        if (busyNum * 2 < liveNum && liveNum > pool->minNum)
        {
            pthread_mutex_lock(&pool->mutexPool);
            pool->exitNum = NUMBER;
            pthread_mutex_unlock(&pool->mutexPool);
            for (int i = 0; i < NUMBER; ++i)
            {
                pthread_cond_signal(&pool->notFull);
            }
        }
    }
    return nullptr;
}

// 线程退出
void ThreadPool::threadExit()//找到要退出的线程id然后对他赋予0
{
    pthread_t tid = pthread_self();
    for (int i = 0; i < maxNum; ++i)
    {
        if (threadIDs[i] == tid)
        {
            cout << "threadExit() function: thread "
                << to_string(pthread_self()) << " exiting..." << endl;
            threadIDs[i] = 0;
            break;
        }
    }
    pthread_exit(NULL);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值