Linux线程池简易实现

一 ThreadPool.hpp

cpp 复制代码
#pragma once

#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>

using namespace std;
struct ThreadInfo
{
    pthread_t tid;
    string threadName;
};
static const int num = 5;
template <class T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_lock);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_lock);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_lock);
    }
    bool IsTasksQueueEmpty()
    {
        return _tasks.empty();
    }
    T Pop()
    {
        T task = _tasks.front();
        _tasks.pop();
        return task;
    }

    std::string GetThreadName(pthread_t tid)
    {
        for (const auto &ti : _threads)
        {
            if (ti.tid == tid)
                return ti.threadName;
        }
        return "None";
    }
    static void *HandlerTask(void *args)
    {
        // 局部变量
        ThreadPool *tp = static_cast<ThreadPool *>(args);
        std::string name = tp->GetThreadName(pthread_self());
        cout << "create a new thread: " << endl;
        while (1)
        {
            // 临界资源_tasks,访问时需要加锁
            tp->Lock();
            while (tp->IsTasksQueueEmpty()) // 有任务才能继续执行,误唤醒
            {
                tp->ThreadSleep();
            }
            T t = tp->Pop();
            tp->Unlock();
            t(); // 处理任务
            std::cout << name << " run, "
                      << "result: " << t.GetResult() << std::endl;
        }
    }

public:
    ThreadPool(int size = num)
        : _threads(size)
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
        for (int i = 0; i < _threads.size(); ++i)
        {
            pthread_join(_threads[i].tid, nullptr);
        }
    }
    void start()
    {
        // 循环创建多线程
        for (int i = 0; i < _threads.size(); ++i)
        {
            _threads[i].threadName = "thread-" + to_string(i);
            pthread_create(&(_threads[i].tid), nullptr,
                           HandlerTask, this);
        }
    }
    void Push(const T &in)
    {
        Lock();
        _tasks.push(in);
        Wakeup();
        Unlock();
    }

private:
    vector<ThreadInfo> _threads;
    queue<T> _tasks;

    pthread_mutex_t _lock;
    pthread_cond_t _cond;
};

二 Task.hpp

cpp 复制代码
#pragma once
#include <iostream>
#include <string>

std::string opers="+-*/%";

enum{
    DivZero=1,
    ModZero,
    Unknown
};

class Task
{
public:
    //Task(){}
    Task(int x=0, int y=0, char op=opers[0]) : data1_(x), data2_(y), oper_(op), result_(0), exitcode_(0)
    {
    }
    void run()
    {
        switch (oper_)
        {
        case '+':
            result_ = data1_ + data2_;
            break;
        case '-':
            result_ = data1_ - data2_;
            break;
        case '*':
            result_ = data1_ * data2_;
            break;
        case '/':
            {
                if(data2_ == 0) exitcode_ = DivZero;
                else result_ = data1_ / data2_;
            }
            break;
        case '%':
           {
                if(data2_ == 0) exitcode_ = ModZero;
                else result_ = data1_ % data2_;
            }            break;
        default:
            exitcode_ = Unknown;
            break;
        }
    }
    void operator ()()
    {
        run();
    }
    std::string GetResult()
    {
        std::string r = std::to_string(data1_);
        r += oper_;
        r += std::to_string(data2_);
        r += "=";
        r += std::to_string(result_);
        r += "[code: ";
        r += std::to_string(exitcode_);
        r += "]";

        return r;
    }
    std::string GetTask()
    {
        std::string r = std::to_string(data1_);
        r += oper_;
        r += std::to_string(data2_);
        r += "=?";
        return r;
    }
    ~Task()
    {
    }

private:
    int data1_;
    int data2_;
    char oper_;

    int result_;
    int exitcode_;
};

三 main.cpp

cpp 复制代码
#include"ThreadPool.hpp"
#include"Task.hpp"
#include<ctime>
int main()
{
    ThreadPool<Task> *tp = new ThreadPool<Task>(5);
    tp->start();
    srand(time(nullptr)^getpid());
    usleep(5000);
    cout<<"threadPool start!"<<endl;
    while(1)
    {
        // 1 创建任务,发送任务
        int x = rand()%10+1;
        int y = rand()%10;
        char op = opers[rand()%opers.size()];
        Task t(x,y,op);

        // 2 发送任务,多线程并发执行任务
        tp->Push(t);
        std::cout << "main thread make task: " << t.GetTask() << std::endl;

        sleep(1);
    }
}
相关推荐
basketball61627 分钟前
Linux C 管道文件操作
linux·运维·c语言
浩浩测试一下1 小时前
Windows 与 Linux 内核安全及 Metasploit/LinEnum 在渗透测试中的综合应用
linux·运维·windows·web安全·网络安全·系统安全·安全架构
stark张宇1 小时前
Linux 文件创建、删除、移动、复制基础知识整理
linux·服务器·centos
Jiangnan_Cai2 小时前
Linux 系统 docker 部署 Dify
linux·docker·大模型·dify
Two_brushes.3 小时前
【linux网络】深入理解 TCP/UDP:从基础端口号到可靠传输机制全解析
linux·运维·服务器
FJW0208143 小时前
【Linux】系统引导修复
linux·运维·服务器
慌糖4 小时前
CentOS 安装 Redis 简明指南
linux·redis·centos
设计师小聂!4 小时前
linux常用命令(一)
linux·运维·服务器
hnlucky4 小时前
《Nginx + 双Tomcat实战:域名解析、静态服务与反向代理、负载均衡全指南》
java·linux·服务器·前端·nginx·tomcat·web
cui_win4 小时前
【网络】Linux 内核优化实战 - net.ipv4.tcp_congestion_control
linux·网络·tcp/ip