C++Thread封装

实现一个C++的对pthread的封装基类,来实现对线程的启动,分离,等待结束以及取消操作,可以在派生类中定义run函数来实现线程的具体操作

定义头文件

cpp 复制代码
//
// Created by crab on 2024/9/24.
//

#ifndef THREAD_H
#define THREAD_H

#include <pthread.h>

class Thread {
public:
    virtual ~Thread();

    bool start(void *arg);
    bool detach();
    bool join();
    bool cancel();
    [[nodiscard]] pthread_t getThreadId() const;

protected:
    Thread();
    virtual void run(void *arg) = 0;

private:
    static void *threadRun(void *);

private:
    void *mArg;
    bool mIsStart;
    bool mIsDetach;
    pthread_t mThreadId{};
};


#endif //THREAD_H

实现文件

cpp 复制代码
//
// Created by crab on 2024/9/24.
//
#include "Thread.h"


Thread::Thread() :
    mArg(NULL),
    mIsStart(false),
    mIsDetach(false)
{
    /*
     初始化类的成员变量
     线程函数的参数为NULL, 线程启动状态和分离状态均设置为false
     */

}


Thread::~Thread() {
    //检查线程是否已经启动且也没有分离,如果是,调用detach来分离线程,避免对象销毁后产生资源泄露
    if(mIsStart == true && mIsDetach == false)
        detach();
}


bool Thread::start(void *arg) {
    //用于启动线程
    mArg = arg;

    //创建新线程,线程的入口函数为静态成员函数threadRun,并将当前Thread对象作为参数传递给线程,如果失败,返回false
    if(pthread_create(&mThreadId, NULL, threadRun, this))
        return false;
    //标记线程已启动
    mIsStart = true;
    return true;
}

bool Thread::detach() {

    //如果线程没有启动,返回false
    if(mIsStart != true)
        return false;
    //如果线程已经分离,返回true
    if(mIsDetach == true)
        return true;
    //调用pthread_detach将线程设置为分离状态,成功则标记mIsDetach为true,失败返回false
    if(pthread_detach(mThreadId))
        return false;

    mIsDetach = true;
    return true;

}


bool Thread::join()
{
    //等待线程结束
    //如果没有启动或者已经分离,则返回false
    if(mIsStart != true || mIsDetach == true)
        return false;
    //如果join失败,返回false,否则返回true
    if(pthread_join(mThreadId, NULL))
        return false;

    return true;
}

bool Thread::cancel() {
    //用于取消线程
    //如果线程没有启动,返回false
    if(mIsStart != true)
        return false;

    //取消成功mIsStart设置为false,返回true,失败则返回false
    if(pthread_cancel(mThreadId))
        return false;

    mIsStart = false;

    return true;

}

pthread_t Thread::getThreadId() const {
    //用于获取线程的描述符
    return mThreadId;
}


void *Thread::threadRun(void *arg) {
    //作为线程的入口点 arg时指向对象Thread的指针,调用派生类中实现的run()方法,来执行具体的线程任务
    Thread* thread = (Thread*)arg;
    thread->run(thread->mArg);
    return NULL;

}

派生类以及测试

cpp 复制代码
#include <iostream>
#include "src/Schedule/Thread.h"

class TestThread : public Thread {
protected:
    virtual void run(void *arg) override {
        int* num = static_cast<int*>(arg);
        for(int i=0; i<*num; ++i) {
            std::cout<<"Thread is runing:"<<i<<std::endl;
        }
    }
};

int main() {
    TestThread thread;

    int count = 5;  // 线程将运行 5 次
    if (thread.start(&count)) {
        std::cout << "Thread started successfully!" << std::endl;

        // 使用 join() 等待线程结束
        if (thread.join()) {
            std::cout << "Thread joined successfully!" << std::endl;
        } else {
            std::cerr << "Failed to join thread." << std::endl;
        }
    } else {
        std::cerr << "Failed to start thread." << std::endl;
    }

    // 测试 detach(不等待线程结束)
    TestThread detachThread;
    if (detachThread.start(&count)) {
        std::cout << "Thread (detached) started successfully!" << std::endl;
        if (detachThread.detach()) {
            std::cout << "Thread detached successfully!" << std::endl;
        } else {
            std::cerr << "Failed to detach thread." << std::endl;
        }
    } else {
        std::cerr << "Failed to start detached thread." << std::endl;
    }

    return 0;
}

运行结果

/home/crab/project/clion_work/RTPServer/cmake-build-debug-remote-host/RTPServer

Thread started successfully!

Thread is runing:0

Thread is runing:1

Thread is runing:2

Thread is runing:3

Thread is runing:4

Thread joined successfully!

Thread (detached) started successfully!

Thread detached successfully!

Process finished with exit code 0

相关推荐
freyazzr24 分钟前
Leetcode刷题 | Day67_图论12_Floyd算法 / A*算法
数据结构·c++·算法·leetcode·图论
whoarethenext28 分钟前
c/c++的opencv椒盐噪声
c语言·c++·opencv
乌鸦94433 分钟前
《STL--list的使用及其底层实现》
开发语言·c++·list·list介绍使用及其底层实现
楼田莉子1 小时前
C++学习之STL学习:string类常用接口的模拟实现
开发语言·数据结构·c++·学习·算法·stl
点云SLAM1 小时前
C++中IO类(iostream、fstream和sstream)知识详解和应用
c++·文件读写操作·fstream·c++中io类·iostream应用·文本io操作应用
鲨鱼吃橘子1 小时前
HTTPS协议原理
网络·c++·网络协议·算法·http·https
一伦明悦დ2 小时前
C++编程单例模式详细解释---模拟一个网络配置管理器,负责管理和分发网络连接参数
数据库·c++·单例模式
Dovis(誓平步青云)5 小时前
破解C/C++内存分配与管理:内存对象模型硬核剖析
开发语言·c++·内存管理·解读
Uncertainty!!9 小时前
C++编译/链接模型
c++·链接·编译
CodeWithMe10 小时前
【C/C++】线程状态以及转换
java·c语言·c++