创建自己的CriticalSection和Lock

本文探讨如何在编程中创建自定义的CriticalSection类和Lock机制,深入理解线程同步和互斥访问的概念,以提高多线程环境下的代码安全性。
摘要由CSDN通过智能技术生成
Lockable.h: CriticalSection的抽象父类
class LockableObject
{
      public:
            LockableObject(){}
            virtual ~LockableObject(){}
            virtual void Lock() = 0;
            virtual void Unlock() = 0;
};
 
CriticalSection.h
#include "LockableObject.h"
#include <windows.h>
 
class CriticalSection : public LockableObject
{
      public:
            CriticalSection();
            virtual ~CriticalSection();
            virtual void Lock();
            virtual void Unlock();
      private:
            CRITICAL_SECTION mCriticalSection;
};
 
CriticalSection.cpp
#include "CriticalSection.h"
 
CriticalSection::CriticalSection()
{
      InitializeCriticalSection(&mCriticalSection);
}
 
CriticalSection::~CriticalSection()
{
      DeleteCriticalSection(&mCriticalSection);
}
 
void CriticalSection::Lock()
{
      EnterCriticalSection(&mCriticalSection);
}
 
void CriticalSection::Unlock()
{
      LeaveCriticalSection(&mCriticalSection);
}
 
Lock.h
#include "CriticalSection.h"
 
class Lock
{
      public:
            Lock(LockableObject* pLockable);
            ~Lock();
      private:
            LockableObject* mLockable;
};
 
Lock.cpp
#include "Lock.h"
 
Lock::Lock(LockableObject* pLockable)
{
      mLockable = pLockable;
      pLockable->Lock();
}
 
Lock::~Lock()
{
      mLockable->Unlock();
}
     
  <script type=text/javascript> </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type=text/javascript> </script>
Google
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值