2.面向对象编程风格

1. 说明

此博客记录如何以面向对象的方式进行编程,以及如何让线程和线程对象同时销毁

2. 相关代码:

2.1 Thread.h
cpp 复制代码
#ifndef _THREAD_H_
#define _THREAD_H_

#include <pthread.h>

class Thread
{
public:
    Thread();
    virtual ~Thread();

    void Start();
    void Join();

    void SetAutoDelete(bool autoDelete);

private:
    static void* ThreadRoutine(void* arg);
    virtual void Run() = 0;
    pthread_t _threadId;

    bool _autoDelete;
};

#endif
2.2 Thread.cpp
cpp 复制代码
#include "Thread.h"
#include <iostream>
using namespace std;

Thread::Thread() : _autoDelete(false)
{
    cout << "Thread() ..." << endl;
}

Thread:: ~Thread()
{
    cout << "~Thread() ..." << endl;
}

void Thread::Start()
{
    //创建一个线程,指定线程入口函数ThreadRoutine,参数为this指针(指向实际对象本身)
    pthread_create(&_threadId, nullptr, ThreadRoutine, this);
}
void Thread::Join()
{
    //以阻塞的形式等待指定的线程终止
    pthread_join(_threadId,nullptr);
}

void* Thread::ThreadRoutine(void* arg)
{
    //将传递过来的对象指针转换为Thread*(基类)类型
    //即基类指针thread指向了派生类对象
    Thread* thread = static_cast<Thread*>(arg);
    //利用虚函数多态,使用基类指针调用子类对象的函数
    //也可以理解为此时的基类相当于一个库,回调了子类中的虚函数
    thread->Run();
    //当子类对象run函数执行完毕后,自动删除当前线程
    if(thread->_autoDelete){
        delete thread;
    }
    return nullptr;
}

void Thread::SetAutoDelete(bool autoDelete)
{
    _autoDelete = autoDelete;
}
2.3 Thread.h
cpp 复制代码
#include "Thread.h"
#include <iostream>
#include <unistd.h>

using namespace std;

class TestThread : public Thread
{
public:
    TestThread(int count) : _count(count)
    {
        cout << "TestThread() ..." << endl;
    }
    ~TestThread()
    {
        cout << "~TestThread() ..." << endl;
    }
    void Run()
    {
        while (_count--)
        {
            cout << "this is a test ..." << endl;
            sleep(1);
        }
        
    }
    int _count;
};

int main()
{
    /*
    TestThread t(5);
    t.Start();//隐式的传递了一个参数this(&t --> 指向对象本身)
    t.Join();
    */
    //线程对象和线程本身销毁的时间并不同步
    //使用下述方式实现线程对象和线程本身同时销毁
    TestThread* t2 = new TestThread(5);
    t2->SetAutoDelete(true);
    t2->Start();
    t2->Join();

    cout << "主线程运行结束..." << endl;

    return 0;
}
相关推荐
欧先生^_^40 分钟前
Linux内核可配置的参数
linux·服务器·数据库
若风的雨1 小时前
【deekseek】P2P通信路由过程
服务器·网络协议·p2p
海尔辛1 小时前
学习黑客5 分钟读懂Linux Permissions 101
linux·学习·安全
Python私教1 小时前
征服Rust:从零到独立开发的实战进阶
服务器·开发语言·rust
王RuaRua2 小时前
[数据结构]5. 栈-Stack
linux·数据结构·数据库·链表
曼岛_2 小时前
[架构之美]linux常见故障问题解决方案(十九)
linux·运维·架构
tan180°2 小时前
Linux进程信号处理(26)
linux·c++·vscode·后端·信号处理
大神的风范3 小时前
从0开始学linux韦东山教程第三章问题小结(4)
linux·服务器
sz66cm3 小时前
Linux基础 -- SSH 流式烧录与压缩传输笔记
linux·笔记·ssh
YOYO--小天3 小时前
RS485和RS232 通信配置
linux·嵌入式硬件