c++线程池版二

基于版一修改,减少了延时,补充了内存释放,增加了注释

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <thread>

/** 任务函数:function_param-任务函数的参数(指针,外部需动态malloc申请后传入,不用管释放,内部会释放) */
typedef void( *TaskFunction)(void *function_param);

/** 线程池 */
class ThreadPool
{
public:
    ThreadPool();
    ~ThreadPool();

    /** 开始:MaxThreadNum-最大线程数,_MaxWaitTaskNum-最大等待中任务数量:返回false表示管理线程创建失败 */
    bool start(int _MaxThreadNum = 10, int _MaxWaitTaskNum = 10000);
    /** 结束 */
    void stop();
    /** 添加任务:_task_function-任务函数,_function_param-任务函数参数:返回0-成功,-1-传入参数存在空值,-2-结束标识为true,-3-等待中的任务数量已达上限 */
    int AddTask(TaskFunction _task_function, void *_function_param);

private:
    /** 最大线程数 */
    int MaxThreadNum;
    /** 最大等待中任务数量 */
    int MaxWaitTaskNum;
    /** 结束标识 */
    bool StopMark;
    /** 管理线程对象 */
    std::thread ThreadManage;

    /** 管理函数 */
    void ManageFunction();
};

#endif
 

#include "ThreadPool.h"
#include <queue>
#include <mutex>

/** 线程任务 */
class ThreadTask
{
public:
    ThreadTask();
    ThreadTask(TaskFunction _task_function, void *_function_param);
    ~ThreadTask();

    /** 任务函数 */
    TaskFunction task_function;
    /** 任务函数的参数 */
    void *function_param;
};

ThreadTask::ThreadTask()
{
    task_function = nullptr;
    function_param = nullptr;
}

ThreadTask::ThreadTask(TaskFunction _task_function, void *_function_param)
{
    task_function = _task_function;
    function_param = _function_param;
}

ThreadTask::~ThreadTask()
{
    if (function_param != nullptr)
    {
        free(function_param);
        function_param = nullptr;
    }
}

/** 任务队列 */
static std::queue<ThreadTask *> s_QueueTask;
/** 任务队列锁 */
static std::mutex s_MutexQueueTask;
/** 条件变量 */
static std::condition_variable s_condition_variable;

/** 工作线程 */
class ThreadWork
{
public:
    ThreadWork();
    ~ThreadWork();

    /** 线程 */
    std::thread _std_thread;
    /** 线程状态:true-主动结束线程,false-默认 */
    bool _stop_mark;
};

ThreadWork::ThreadWork()
{
    _stop_mark = false;
}

ThreadWork::~ThreadWork()
{
    _stop_mark = true;
    if (_std_thread.joinable() == true)
    {
        _std_thread.join();
    }
}

/** 工作线程队列 */
static std::vector<ThreadWork *> s_VectorThreadWork;

/** 工作函数:param-参数 */
static void WorkFunction(void *param)
{
    printf("WorkFunction:thread %d begin\n", std::this_thread::get_id());
    ThreadWork *tw = (ThreadWork *)param;
    while (tw->_stop_mark == false)
    {
        ThreadTask *tt = nullptr;
        {
            std::lock_guard<std::mutex> slgsm(s_MutexQueueTask);
            if (s_QueueTask.size() > 0)
            {
                tt = s_QueueTask.front();
                s_QueueTask.pop();
            }
        }
        if (tt == nullptr)
        {
            std::unique_lock<std::mutex> sulsm(s_MutexQueueTask);
            s_condition_variable.wait_for(sulsm, std::chrono::seconds(1));
        }
        else
        {
            tt->task_function(tt->function_param);
            delete tt;
            tt = nullptr;
        }
    }
    printf("WorkFunction:thread %d end\n", std::this_thread::get_id());
}

ThreadPool::ThreadPool()
{
    MaxThreadNum = 10;
    MaxWaitTaskNum = 10000;
    StopMark = true;
}

ThreadPool::~ThreadPool()
{
    stop();
}

bool ThreadPool::start(int _MaxThreadNum, int _MaxWaitTaskNum)
{
    MaxThreadNum = _MaxThreadNum;
    if (MaxThreadNum < 1)
    {
        MaxThreadNum = 1;
    }
    MaxWaitTaskNum = _MaxWaitTaskNum;
    if (MaxWaitTaskNum < 1)
    {
        MaxWaitTaskNum = 1;
    }
    StopMark = false;
    ThreadManage = std::thread(&ThreadPool::ManageFunction, this);
    if (ThreadManage.joinable() == false)
    {
        StopMark = true;
        return false;
    }

    return true;
}

void ThreadPool::stop()
{
    StopMark = true;
    if (ThreadManage.joinable() == true)
    {
        ThreadManage.join();
    }
    for (size_t i = 0; i < s_VectorThreadWork.size(); i++)
    {
        s_VectorThreadWork.at(i)->_stop_mark = true;
    }
    s_condition_variable.notify_all();
    while (s_VectorThreadWork.empty() == false)
    {
        ThreadWork *tw = s_VectorThreadWork.front();
        s_VectorThreadWork.erase(s_VectorThreadWork.begin());
        delete tw;
        tw = nullptr;
    }
    std::lock_guard<std::mutex> slgsm(s_MutexQueueTask);
    while (s_QueueTask.empty() == false)
    {
        ThreadTask *tt = s_QueueTask.front();
        s_QueueTask.pop();
        delete tt;
        tt = nullptr;
    }
}

int ThreadPool::AddTask(TaskFunction _task_function, void *_function_param)
{
    if (_function_param == nullptr)
    {
        return -1;
    }

    if (_task_function == nullptr)
    {
        free(_function_param);
        _function_param = nullptr;
        return -1;
    }

    if (StopMark == true)
    {
        free(_function_param);
        _function_param = nullptr;
        return -2;
    }

    {
        std::lock_guard<std::mutex> slgsm(s_MutexQueueTask);
        if (s_QueueTask.size() >= MaxWaitTaskNum)
        {
            free(_function_param);
            _function_param = nullptr;
            return -3;
        }

        s_QueueTask.push(new ThreadTask(_task_function, _function_param));
    }
    s_condition_variable.notify_all();
    return 0;
}

void ThreadPool::ManageFunction()
{
    printf("ThreadPool::ManageFunction:thread %d begin\n", std::this_thread::get_id());
    while (StopMark == false)
    {
        size_t QueueTaskSize = 0;
        {
            std::lock_guard<std::mutex> slgsm(s_MutexQueueTask);
            QueueTaskSize = s_QueueTask.size();
        }
        if (QueueTaskSize <= 0)
        {
            if (s_VectorThreadWork.size() > 0)
            {
                ThreadWork *tw = s_VectorThreadWork.front();
                s_VectorThreadWork.erase(s_VectorThreadWork.begin());
                tw->_stop_mark = true;
                s_condition_variable.notify_all();
                delete tw;
                tw = nullptr;
            }
            else
            {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
        else
        {
            s_condition_variable.notify_all();
            if ((s_VectorThreadWork.size() * 2 < QueueTaskSize) && (s_VectorThreadWork.size() < MaxThreadNum))
            {
                ThreadWork *tw = new ThreadWork();
                tw->_std_thread = std::thread(WorkFunction, tw);
                if (tw->_std_thread.joinable() == false)
                {
                    delete tw;
                    tw = nullptr;
                }
                else
                {
                    s_VectorThreadWork.push_back(tw);
                }
            }
        }
    }
    printf("ThreadPool::ManageFunction:thread %d end\n", std::this_thread::get_id());
}
 

#include "ThreadPool.h"

#pragma warning(disable:4996)

struct StructTest
{
    char ca[1024];
    char cb[1024];
    char cc[1024];
    char cd[1024];
    int ia;
    int ib;
    int ic;
    int id;
};

void func(void *pa)
{
    StructTest *st = (StructTest *)pa;
    printf("*****%s %s %s %s %d %d %d %d*****\n", st->ca, st->cb, st->cc, st->cd, st->ia, st->ib, st->ic, st->id);
}

int main()
{
    ThreadPool tp;
    bool br = tp.start();
    printf("br=%d\n", br);
    if (br == true)
    {
        for (size_t i = 0; i < 100; i++)
        {
            StructTest *st = (StructTest *)malloc(sizeof(StructTest));
            memset(st, 0, sizeof(StructTest));
            st->ia = i + 1;
            st->ib = i + 2;
            st->ic = i + 100;
            st->id = i + 200;
            sprintf(st->ca, "num:%d", st->ia);
            sprintf(st->cb, "num:%d", st->ib);
            sprintf(st->cc, "num:%d", st->ic);
            sprintf(st->cd, "num:%d", st->id);
            tp.AddTask(func, (void *)st);
        }
    }
    getchar();
    if (br == true)
    {
        for (size_t i = 0; i < 100; i++)
        {
            StructTest *st = (StructTest *)malloc(sizeof(StructTest));
            memset(st, 0, sizeof(StructTest));
            st->ia = i + 1;
            st->ib = i + 2;
            st->ic = i + 100;
            st->id = i + 200;
            sprintf(st->ca, "num:%d", st->ia);
            sprintf(st->cb, "num:%d", st->ib);
            sprintf(st->cc, "num:%d", st->ic);
            sprintf(st->cd, "num:%d", st->id);
            tp.AddTask(func, (void *)st);
        }
    }
    getchar();
    return 0;
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值