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

相关推荐
CYBEREXP20081 小时前
MacOS M3源代码编译Qt6.8.1
c++·qt·macos
yuanbenshidiaos1 小时前
c++------------------函数
开发语言·c++
yuanbenshidiaos1 小时前
C++----------函数的调用机制
java·c++·算法
tianmu_sama2 小时前
[Effective C++]条款38-39 复合和private继承
开发语言·c++
羚羊角uou2 小时前
【C++】优先级队列以及仿函数
开发语言·c++
姚先生972 小时前
LeetCode 54. 螺旋矩阵 (C++实现)
c++·leetcode·矩阵
FeboReigns2 小时前
C++简明教程(文章要求学过一点C语言)(1)
c语言·开发语言·c++
FeboReigns2 小时前
C++简明教程(文章要求学过一点C语言)(2)
c语言·开发语言·c++
264玫瑰资源库3 小时前
从零开始C++棋牌游戏开发之第二篇:初识 C++ 游戏开发的基本架构
开发语言·c++·架构
_小柏_3 小时前
C/C++基础知识复习(43)
c语言·开发语言·c++