线程池(C++)

个人主页:Lei宝啊

愿所有美好如期而遇


线程池

实现线程类

cpp 复制代码
#pragma once

#include <pthread.h>
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <unistd.h>
#include "sem.hpp"
using namespace std;

class Thread
{
    using func_t = function<void(string)>;

public:
    void Excute()
    {
        _func(_threadname);
    }
public:
    Thread(func_t func, const std::string &name="none-name")
        : _func(func), _threadname(name), _stop(true)
    {}
    static void *threadroutine(void *args) // 类成员函数,形参是有this指针的!!
    {
        Thread *self = static_cast<Thread *>(args);
        self->Excute();
        return nullptr;
    }
    bool Start()
    {
        int n = pthread_create(&_tid, nullptr, threadroutine, this);
        if(!n)
        {
            _stop = false;
            return true;
        }
        else
        {
            return false;
        }
    }
    void Detach()
    {
        if(!_stop)
        {
            pthread_detach(_tid);
        }
    }
    void Join()
    {
        if(!_stop)
        {
            pthread_join(_tid, nullptr);
        }
    }
    std::string name()
    {
        return _threadname;
    }
    void Stop()
    {
        _stop = true;
    }
    ~Thread() {}

private:
    pthread_t _tid;
    std::string _threadname;
    func_t _func;
    bool _stop;
};

任务类

这个就随便写了,用来简单测试。

cpp 复制代码
#include <iostream>
using namespace std;

class Task
{
public:
    void Compare()
    {
        cout << "compare" << endl;
    }

    void operator()()
    {
        Compare();
    }

int a = 1;
int b = 2;

};

线程池类

cpp 复制代码
#include "Thread_pool.hpp"
#include <queue>

const int g_pthreadnum = 6;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

//线程池
template<class T>
class ThreadPool
{
public:
    ThreadPool(int num = g_pthreadnum)
        :pthreadnum(num)
        ,state(false)
        ,waitnum(0)
    {}

    void Everydo(string name)
    {
        while(true)
        {
            Lock();

            while(qtask.empty() && state)
            {
                waitnum++;
                Wait_Pthread();
                waitnum--;
            }

            if(qtask.empty() && !state)
            {
                UnLock();
                cout << name << ": quit" << endl;
                break;
            }

            T task = qtask.front();
            qtask.pop();

            task();

            UnLock();
        }
    }

    bool Push(const T& t)
    {
        Lock();

        bool ret = false;
        if(state)
        {
            qtask.push(t);
            if(waitnum > 0) WakeUp_sigle();

            ret = true;
        }

        UnLock();
        return ret;
    }

    void ThreadInit()
    {
        for(int i=0; i<pthreadnum; i++)
        {
            string name = "pthread-" + to_string(i);
            vthread.emplace_back(bind(&ThreadPool::Everydo, 
            this, placeholders::_1), name);  
            //每个线程都要执行这个方法,这个方法会将任务队列中的任务分配给他们
        }
    }

    void Wait()
    {
        for(auto &e : vthread) e.Join();
    }

    void Quit()
    {
        state = false;
        WakeUp_All();
    }

    void Start()
    {
        state = true;
        for(auto &e : vthread) e.Start();
    }

private:
    //线程池需要什么?线程数量,保存线程的容器
    int pthreadnum;
    vector<Thread> vthread;

    //一个任务队列,创建线程池对象时,线程创建好,我们需要从外部接收任务分配给线程执行
    //我们希望能够接收任意类型的任务,仿函数,函数,lambda表达式等,所以使用模板
    queue<T> qtask;

    //一个状态,控制线程池的退出
    bool state;
    int waitnum;

    void Lock()
    {
        pthread_mutex_lock(&mutex);
    }

    void UnLock()
    {
        pthread_mutex_unlock(&mutex);
    }

    void WakeUp_sigle()
    {
        pthread_cond_signal(&cond);
    }

    void WakeUp_All()
    {
        pthread_cond_broadcast(&cond);
    }

    void Wait_Pthread()
    {
        pthread_cond_wait(&cond, &mutex);
    }
};

测试

相关推荐
熬夜学编程的小王13 分钟前
C++类与对象深度解析(一):从抽象到实践的全面入门指南
c++·git·算法
CV工程师小林15 分钟前
【算法】DFS 系列之 穷举/暴搜/深搜/回溯/剪枝(下篇)
数据结构·c++·算法·leetcode·深度优先·剪枝
蜜桃小阿雯35 分钟前
JAVA开源项目 旅游管理系统 计算机毕业设计
java·开发语言·jvm·spring cloud·开源·intellij-idea·旅游
Benaso36 分钟前
Rust 快速入门(一)
开发语言·后端·rust
zh路西法43 分钟前
基于opencv-C++dnn模块推理的yolov5 onnx模型
c++·图像处理·pytorch·opencv·yolo·dnn·yolov5
wjs202443 分钟前
HTML5 新元素
开发语言
慕明翰1 小时前
Springboot集成JSP报 404
java·开发语言·spring boot
satan–01 小时前
R语言的基本语句及基本规则
开发语言·windows·r语言
-指短琴长-1 小时前
BFS解决多源最短路问题_01矩阵_C++【含多源最短路问题介绍+dist数组介绍】
c++·矩阵·宽度优先
小码农<^_^>1 小时前
c++继承(下)
开发语言·c++