Linux---线程封装

threat.hpp

cpp 复制代码
#ifndef _THREAD_HPP_
#define _THREAD_HPP_
#include <cstring>
#include <iostream>
#include <pthread.h>
#include <string>
#include <cstring>
#include <cstdio>
#include<functional>

namespace Z {

    static int number = 1;
    class thread {
        using func_t = std::function<void()>;
    private:
        void EnableDetach() {
            std::cout << "线程被分离了" << std::endl;
            _isdetach = true;
        }
        void EnableRunning() {
            std::cout << "线程启动" << std::endl;
            _isrunning = true;
        }

        static void *routine(void *args) {
            thread *self = static_cast<thread *>(args);
            self->EnableRunning();
            if(self->_isdetach)
                self->Detach();
            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_func();
            return nullptr;
        }

    public:
        thread(func_t func) : _tid(0), _isdetach(false), _isrunning(false), _ret(nullptr), _func(func)
        {
            _name = "thread-"+std::to_string(number++);
        }

        void Detach() {
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            EnableDetach();
        }

        bool Start() {
            if (_isrunning)
                return false;
            int p = pthread_create(&_tid, nullptr, routine, this);
            if (p != 0) {
                std::cerr << "create threat fail!" << std::endl;
                return false;
            } else {
                {
                    std::cout << _name << "create success" << std::endl;
                    return true;
                }
            }
        }

        void Join() {
            if (_isdetach) {
                std::cout << "线程已分离,无法join" << std::endl;
                return;
            }
            int n = pthread_join(_tid, &_ret);
            if (n != 0) {
                std::cerr << "join 失败了" << strerror(n) << std::endl;
            } else {
                std::cout << "join success" << std::endl;
            }
        }

        bool Stop() {
            if (_isrunning) {
                int n = pthread_cancel(_tid);
                if (n != 0) {
                    std::cerr << "create thread error: " << strerror(n) << std::endl;
                    return false;
                } else {
                    _isrunning = false;
                    std::cout << _name << "stop" << std::endl;
                    return true;
                }
            }
            return true;
        }
        ~thread() {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *_ret;
        func_t _func;
    };

} 

#endif

test.cc

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

using namespace Z;
int main() {
    std::vector<thread> threads;
    for (int i = 0; i < 10; i++) {
        threads.emplace_back([]() {
            while (true) {
                char name[128];
                pthread_getname_np(pthread_self(), name, sizeof(name));
                std::cout << "我是一个新线程" << "name: " << name << std::endl;
                sleep(1);
            }
        });
    }

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

    return 0;
}
相关推荐
---学无止境---9 小时前
Linux中比较两个字符串的前count个字符的汇编实现
linux
给大佬递杯卡布奇诺9 小时前
FFmpeg 基本API avio_read函数内部调用流程分析
c++·ffmpeg·音视频
文火冰糖的硅基工坊9 小时前
[嵌入式系统-115]:鸿蒙操作系统(HarmonyOS)与欧拉操作系统(openEuler)、Linux操作系统的关系、比较及异同如下:
linux·服务器·科技·华为·重构·架构·harmonyos
2401_837088509 小时前
Redis的vim基本操作
linux·编辑器·vim
chao1898449 小时前
基于MATLAB的双摆系统阻抗控制实现
算法
馨谙9 小时前
标题:Linux 系统中的“保险库管理员”:深入浅出理解 /etc/shadow 文件
linux·运维·服务器
liulilittle9 小时前
Y组合子剖析:C++ 中的递归魔法
开发语言·c++·编程语言·函数式编程·函数式·函数编程·y组合子
---学无止境---9 小时前
Linux中zonelist分配策略初始化
linux
撬动未来的支点10 小时前
【Linux内核】Linux系统启动之旅
linux