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

相关推荐
双叶8369 分钟前
(51单片机)矩阵按键密码锁表白(C语言代码编撰)(矩阵按键教程)(LCD1602浅教程)
c语言·开发语言·c++·算法·游戏·矩阵·51单片机
海棠蚀omo34 分钟前
C++笔记-string(下)
开发语言·c++·笔记
天堂的恶魔94639 分钟前
C++ —— 文件操作(流式操作)
c++
dora2 小时前
逼格提起来,使用curl发送网络请求
android·c++
yy_xzz2 小时前
基于条码数据生成校验密码的C++实现方案
开发语言·c++
技术小白Byteman2 小时前
蓝桥刷题note13(排序)
开发语言·数据结构·c++·学习·算法·visualstudio
老歌老听老掉牙2 小时前
C++使用Qt Charts可视化大规模点集
c++·qt·信息可视化·点集
OneQ6663 小时前
C++自学笔记——动态创建对象
c++·笔记·算法
Dream it possible!3 小时前
LeetCode 热题 100_完全平方数(84_279_中等_C++)(动态规划(完全背包))
c++·leetcode·动态规划·完全背包
末央&4 小时前
【C++】vector的底层封装和实现
android·c++