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

相关推荐
你的冰西瓜13 分钟前
C++ 中最短路算法的详细介绍
c++·算法·图论·最短路
<但凡.28 分钟前
数据结构与算法之美:广义表
数据结构·c++·算法
大白的编程日记.2 小时前
【计算机基础理论知识】C++篇(二)
开发语言·c++·学习
C语言小火车2 小时前
野指针:C/C++内存管理的“幽灵陷阱”与系统化规避策略
c语言·c++·学习·指针
凤年徐2 小时前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
踏莎行hyx3 小时前
使用langchain连接llama.cpp部署的本地deepseek大模型开发简单的LLM应用
c++·ai·langchain·大模型·llama.cpp·deepseek
山河木马3 小时前
前端学C++可太简单了:双冒号 :: 操作符
前端·javascript·c++
乌萨奇也要立志学C++4 小时前
【C++详解】STL-list模拟实现(深度剖析list迭代器,类模板未实例化取嵌套类型问题)
c++·list
闻缺陷则喜何志丹4 小时前
【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
数据结构·c++·前缀和·宽度优先·洛谷·并集查找
序属秋秋秋5 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习