2.面向对象编程风格

1. 说明

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

2. 相关代码:

2.1 Thread.h
#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
#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
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山间点烟雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值