码迷,mamicode.com
首页 > 其他好文 > 详细

一个关于锁的类

时间:2021-06-08 23:22:55      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:vat   end   public   unlock   c++   做自己   ase   class   rtu   

  由于C++编程中,经常用到多线程编程。这样的话就得用到锁,因此就把锁的操作封装到一个类中,实现如下:

  #include <pthread.h>

  typedef pthread_mutex_t CRITICAL_SECTION;

  class LockBase
  {
  public:
    LockBase();
    virtual ~LockBase();
    virtual void Lock() = 0;
    virtual void UnLock() = 0;
  }; 

  class DerivedLock : public LockBase
  {
  public:
    DerivedLock();
    virtual ~DerivedLock();
    virtual void Lock();
    virtual void UnLock();
    virtual void Destroy();
  private:
    CRITICAL_SECTION m_cs;
  };  

  class SafeLock
  {
  public:
    SafeLock();
    SafeLock(LockBase* pLock);
    virtual ~SafeLock();
  private:
    LockBase *m_pLock;
  };

==============================类的实现如下==============================================

  LockBase::LockBase()
  {

  }

  LockBase::~LockBase()
  {

  }

  

  DerivedLock::DerivedLock()
  {
    pthread_mutex_init(&m_cs, NULL);
  }

  DerivedLock::~DerivedLock()
  {
    pthread_mutex_destroy(&m_cs);
  }

  void DerivedLock::Lock()
  {
    pthread_mutex_lock(&m_cs);
  }

  void DerivedLock::UnLock()
  {
    pthread_mutex_unlock(&m_cs);
  }

  void DerivedLock::Destroy()
  {
    pthread_mutex_destroy(&m_cs);
  }

  SafeLock::SafeLock()
  {
    m_pLock = NULL;
  }

  SafeLock::SafeLock(LockBase* pLock)
  {
    m_pLock = pLock;
    if (m_pLock)
    {
      m_pLock->Lock();
    }
  }

  SafeLock::~SafeLock()
  {
    if (m_pLock)
    {
      m_pLock->UnLock();
      m_pLock = NULL;
    }
  }

 

  最后的使用如下:

  DerivedLock m_csMosending;

  int  main()

  {

    if(1)  

    {

      SafeLock safelock(&m_csMosending);

      //做自己所要的操作......

    }

    return  0;

  }

一个关于锁的类

标签:vat   end   public   unlock   c++   做自己   ase   class   rtu   

原文地址:https://www.cnblogs.com/Unclebigdata/p/14862838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!