在网络编程的时候往往需要对Linux下原生的pthread库中的函数进行封装,使其使用起来更加方便,封装方法一般有两种:面向对象和基于对象,下面将分别介绍这两种方式,最后统一分析这两种方式的优缺点:

面向对象:

面向对象的封装方式是通过虚函数提供回调功能,我们创建一个Thread类,然后设置一个run虚函数,使用时只需要重载这个类并实现其中的虚函数即可:

具体实现如下:

//------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* args);
    virtual void run() = 0;
    pthread_t threadId_;
    bool autoDelete_;
};

#endif
详细实现如下:
//---------thread.c-------------------

#include "thread.h"
#include <iostream>
using namespace std;

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

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

void* Thread::threadRoutine(void* arg)
{
    Thread* thread = static_cast<Thread*>(arg);
    thread->run();

    if (thread->autoDelete_)
    {
        delete thread;
    }

    return NULL;
}


void Thread::start()
{
    pthread_create(&threadId_,NULL, threadRoutine,this);
}

void Thread::join()
{
    pthread_join(threadId_, NULL);
}

void Thread::setAutoDelete(bool autoDelete)
{
    autoDelete_ = autoDelete;
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2021-11-20
猜你喜欢
  • 2021-09-05
  • 2022-12-23
  • 2021-08-21
  • 2021-05-31
  • 2021-10-13
相关资源
相似解决方案