找个工作

大并发服务架构-面向对象编程风格

2021-04-17  本文已影响0人  吃掉夏天的怪物

https://www.bilibili.com/video/BV1Zt411K7Gg?p=8&spm_id_from=pageDriver
muduo库只暴露抽象类不暴露具体类,也不使用虚函数作为接口,说明是基于对象的思想。

面向对象风格的线程类的封装

线程类的封装.png

Thread 抽象类,不能实例化对象

# ifndef _THREAD_H_
#define _THREAD_H_

class Thread // 多态基类,因此析构函数必须得是virtual
{
public:
  Thread();
  virtual ~Thread();//纯虚析构函数

  void Start();
  void Join();
  void SetAutoDelete(bool autoDelete);

private:
  //static void*(start_routine)(void*)//加了static这个函数就没有隐含的历史指针了
static void* ThreadRoutine(void* arg);
virtual void Run() = 0;
  pthread_t threadId_;
  bool autoDelete_; //新增一个属性表示,是否自动销回
}
#endif//_THREAD_H 
#include"Thread.h"
#include<iostream>
using namespace std;
Thread::Thread():autoDelete_(false)
{
  cout<<"Thread..."<<endl;
}
Thread::~Thread()
{
   cout<<"~Thread..."<<endl;
}
void Thread::Start()
{
  pthread_create(&threadId_,NULL,ThreadRoutine, this);//this 一定指向的派生类
}
void Thread::Join()//等待
{
  pthread_join(threadId_,NULL);
}
void* Thread::ThreadRoutine(void* arg) // 静态成员函数不能调用非静态的成员函数,也就是说没有this指针
{
  Thread* thread = static_cast<Thread*>(arg);//把派生类转换为基类指针,基类指针指向派生类对象
  thread->Run();//并且调用它,使用到了虚函数的多态
  if(thread->autoDelete_)
    delete thread;
  return NULL; 
};
void* Thread::SetAutoDelete(bool autoDelete) 
{
  autoDelete_ = autoDelete;
}

man
Run是普通得成员函数,隐含的第一个参数是 Thread*(this)
调用的时候是thiscall约定而start_routine

man pthread_create.png
#include"Thread.h"
#include<unistd.h>
#include<iostream>
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(void)
{
 TestThread t(5); //派生类对象
  t.start();//隐含了&t
  t.Join();
//如果 t.Run();就还是在主线程上运行,并不算一个线程
  return 0;
}

需要连接线程库target_link_libriaries(Thread_test pthread)
虚函数 具有 回调的 功能
线程对象的生命周期 与 线程的生命周期 是不一样的。线程执行完毕,线程对象并没有被销回。
现在想实现,线程执行完毕,线程对象能自动销毁 。
因此需要动态创建对象才可以

int main(void)
{
 /*TestThread t(5); //派生类对象
  t.start();//隐含了&t
  t.Join();
//如果 t.Run();就还是在主线程上运行,并不算一个线程
  return 0;*/
   TestThread* t2 = new TestThread(5);
    t2->SetAutoDelete(true);
    t2->Start();
    t2->join();
    for(;;)
      pause();
    return 0;
}

线程池
线程如果执行结束,自动销回线程对象(增加一个属性autoDelete_(表示是否自动销毁)

上一篇下一篇

猜你喜欢

热点阅读