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

相关推荐
ULTRA??17 分钟前
C加加中的结构化绑定(解包,折叠展开)
开发语言·c++
凌云行者1 小时前
OpenGL入门005——使用Shader类管理着色器
c++·cmake·opengl
凌云行者1 小时前
OpenGL入门006——着色器在纹理混合中的应用
c++·cmake·opengl
~yY…s<#>1 小时前
【刷题17】最小栈、栈的压入弹出、逆波兰表达式
c语言·数据结构·c++·算法·leetcode
可均可可2 小时前
C++之OpenCV入门到提高004:Mat 对象的使用
c++·opencv·mat·imread·imwrite
白子寰2 小时前
【C++打怪之路Lv14】- “多态“篇
开发语言·c++
小芒果_012 小时前
P11229 [CSP-J 2024] 小木棍
c++·算法·信息学奥赛
gkdpjj3 小时前
C++优选算法十 哈希表
c++·算法·散列表
王俊山IT3 小时前
C++学习笔记----10、模块、头文件及各种主题(一)---- 模块(5)
开发语言·c++·笔记·学习
-Even-3 小时前
【第六章】分支语句和逻辑运算符
c++·c++ primer plus