【Linux】使用C++对线程进行封装

这里直接看代码就行:

第一个版本:

cpp 复制代码
#pragma once
#include <iostream>
#include <functional>
#include <pthread.h>



namespace ThreadModule
{
    static int gnumber = 1;
    using callback_t = std::function<void ()>;//重点 

    enum class TSTATUS//线程状态
    {
        THREAD_NEW,
        THREAD_RUNNING,
        THREAD_STOP
    };

    std::string StatusString(TSTATUS s)
    {
        switch (s)
        {
        case TSTATUS::THREAD_NEW:
            return "THREAD_NEW";
        case TSTATUS::THREAD_RUNNING:
            return "THREAD_RUNNING";
        case TSTATUS::THREAD_STOP:
            return "THREAD_STOP";
        }
        return nullptr;
    }            

    std::string isJoin(bool joinable)
    {
        return joinable ? "true" : "false";
    }

    class Thread
    {
        private:

        void ToRuning()
        {
            _status = TSTATUS::THREAD_RUNNING;
        }

        void ToStop()
        {
            _status = TSTATUS::THREAD_STOP;
        }

        static void* ThreadRoutine(void* args)//static : 取消 this 指针对该函数的干扰
        {
            Thread *self = static_cast<Thread*>(args);
            pthread_setname_np(self->_tid,self->_name.c_str());//设置线程名
            self->_cb();
            self->ToStop();
            return nullptr;
        }

    public:
        Thread(callback_t cb)
        :_tid(-1),_status(TSTATUS::THREAD_NEW),_joinable(true),_cb(cb),_result(nullptr)
        {
            _name = "Thread_" + std::to_string(gnumber++);
        }

        ~Thread()
        {}

        bool Start()
        {
            int n = pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n != 0) return false;
            ToRuning();
            return true;
        }

        void Join()
        {
            if (_joinable)
            {
                int n = pthread_join(_tid, &_result);
                if (n != 0)
                {
                    std::cerr << "join error: " << n << std::endl;
                    return;
                }
                (void)_result;
                _status = TSTATUS::THREAD_STOP;
            }
            else
            {
                std::cerr << "error, thread join status : " << _joinable << std::endl;
            }
        }

        void Detach()
        {
            if(_status == TSTATUS::THREAD_RUNNING && _joinable)
            {
                pthread_detach(_tid);
                _joinable = false;
            }
            else std::cout << "detach " << _name << "failed" << std::endl;
        }

        void Stop()
        {
            
        }

        void Die()
        {
            if(_status == TSTATUS::THREAD_RUNNING)
            {
                pthread_cancel(_tid);
                _status = TSTATUS::THREAD_STOP;
            }
        }

        void PrintInfo()
        {
            std::cout << "thread name: " << _name << std::endl;
            std::cout << "thread _tid: " << _tid << std::endl;
            std::cout << "thread _status: " << StatusString(_status) << std::endl;
            std::cout << "thread _joinable: " << isJoin(_joinable) << std::endl;
        }

    private:
        std::string _name;
        pthread_t _tid;
        TSTATUS _status;
        bool _joinable;
        callback_t _cb;//用户自定义线程的执行函数
        void* _result;//线程的退出信息
    };

} // namespace ThreadModule

第二个版本:

cpp 复制代码
#pragma once
#include <iostream>
#include <functional>
#include <pthread.h>



namespace ThreadModule
{
    static int gnumber = 1;
    template<class T>
    using callback_t = std::function<void (T&)>;//重点 

    enum class TSTATUS//线程状态
    {
        THREAD_NEW,
        THREAD_RUNNING,
        THREAD_STOP
    };

    std::string StatusString(TSTATUS s)
    {
        switch (s)
        {
        case TSTATUS::THREAD_NEW:
            return "THREAD_NEW";
        case TSTATUS::THREAD_RUNNING:
            return "THREAD_RUNNING";
        case TSTATUS::THREAD_STOP:
            return "THREAD_STOP";
        }
        return nullptr;
    }            

    std::string isJoin(bool joinable)
    {
        return joinable ? "true" : "false";
    }

    template<class T>
    class Thread
    {
        private:

        void ToRuning()
        {
            _status = TSTATUS::THREAD_RUNNING;
        }

        void ToStop()
        {
            _status = TSTATUS::THREAD_STOP;
        }

        static void* ThreadRoutine(void* args)//static : 取消 this 指针对该函数的干扰
        {
            Thread<T> *self = static_cast<Thread<T>*>(args);
            pthread_setname_np(self->_tid,self->_name.c_str());//设置线程名
            self->_cb(self->_data);
            self->ToStop();
            return nullptr;
        }

    public:
        Thread(callback_t<T> cb,const T& data)
        :_tid(-1)
        ,_status(TSTATUS::THREAD_NEW)
        ,_joinable(true),_cb(cb)
        ,_result(nullptr)
        ,_data(data)
        {
            _name = "Thread_" + std::to_string(gnumber++);
        }

        ~Thread()
        {}

        bool Start()
        {
            int n = pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n != 0) return false;
            ToRuning();
            return true;
        }

        void Join()
        {
            if (_joinable)
            {
                int n = pthread_join(_tid, &_result);
                if (n != 0)
                {
                    std::cerr << "join error: " << n << std::endl;
                    return;
                }
                (void)_result;
                _status = TSTATUS::THREAD_STOP;
            }
            else
            {
                std::cerr << "error, thread join status : " << _joinable << std::endl;
            }
        }

        void Detach()
        {
            if(_status == TSTATUS::THREAD_RUNNING && _joinable)
            {
                pthread_detach(_tid);
                _joinable = false;
            }
            else std::cout << "detach " << _name << "failed" << std::endl;
        }

        void Stop()
        {
            
        }

        void Die()
        {
            if(_status == TSTATUS::THREAD_RUNNING)
            {
                pthread_cancel(_tid);
                _status = TSTATUS::THREAD_STOP;
            }
        }

        void PrintInfo()
        {
            std::cout << "thread name: " << _name << std::endl;
            std::cout << "thread _tid: " << _tid << std::endl;
            std::cout << "thread _status: " << StatusString(_status) << std::endl;
            std::cout << "thread _joinable: " << isJoin(_joinable) << std::endl;
        }

    private:
        std::string _name;
        pthread_t _tid;
        TSTATUS _status;
        bool _joinable;
        callback_t<T> _cb;//用户自定义线程的执行函数
        void* _result;//线程的退出信息
        T _data;
    };

} // namespace ThreadModule

测试封装的线程:

cpp 复制代码
#include "Thread_version1.hpp"
#include <unistd.h>
#include <vector>

class Task
{
public:
    Task(int x, int y)
        : _x(x), _y(y)
    {
    }

    void Execute()
    {
        _result = _x + _y;
    }

    void Print()
    {
        std::cout << _x << "+" << _y << "=" << _result << std::endl;
    }

private:
    int _x;
    int _y;
    int _result;
};

// void routine(int cnt)
// {
//     char name[64];
//     pthread_getname_np(pthread_self(),name,sizeof(name));

//     int cnt = 10;
//     while(true)
//     {
//         std::cout << "new thread running: " << name << "count :" << std::endl;
//         sleep(1);
//     }
// }

int main()
{
    //构建任务
    srand(time(nullptr) ^ getpid());
    const int num = 10;

    std::vector<Task> tasks;
    for(int i = 0; i < 10;i++)
    {
        tasks.emplace_back(rand()%10 + 1,3);
    }

    std::vector<ThreadModule::Thread> threads;
    for(int i = 0;i < 10;i++)
    {
        threads.emplace_back([i,&tasks](){
            tasks[i].Execute();
        });
    }

    for(auto& t : threads)
    {
        t.Start();
    }

    for(auto& t : threads)
    {
        t.Join();
        t.PrintInfo();
    }

    for(auto& t : tasks)
    {
        t.Print();
    }

////////////////////////////////////////////////////
    // ThreadModule::Thread<int> t(routine,10);//关于可以传多个参数问题,可以传个类过去,这个类里面有多个类型变量
    // sleep(1);
    // t.Start();//创建线程

    // sleep(5);
    // t.Die();//杀掉线程

    // sleep(1);

    // t.Join();//等待线程

    // t.PrintInfo();//打印线程信息
    return 0;
}
相关推荐
清酒难咽11 小时前
算法案例之递归
c++·经验分享·算法
Rabbit_QL11 小时前
【水印添加工具】从零设计一个工程级 Python 图片水印工具:WaterMask 架构与实现
开发语言·python
天“码”行空11 小时前
简化Lambda——方法引用
java·开发语言
z203483152011 小时前
C++对象布局
开发语言·c++
Beginner x_u12 小时前
如何解释JavaScript 中 this 的值?
开发语言·前端·javascript·this 指针
Nick.Q12 小时前
vim插件的管理与离线安装
linux·编辑器·vim
java1234_小锋12 小时前
Java线程之间是如何通信的?
java·开发语言
张张努力变强12 小时前
C++ Date日期类的设计与实现全解析
java·开发语言·c++·算法
沉默-_-12 小时前
力扣hot100滑动窗口(C++)
数据结构·c++·学习·算法·滑动窗口
feifeigo12313 小时前
基于EM算法的混合Copula MATLAB实现
开发语言·算法·matlab