我写的一个锁封装类

文件 CWin32CriticalSection.h

#pragma once


class CWin32CriticalSection
{
public:

 CWin32CriticalSection(CRITICAL_SECTION& csInUse):m_csInUse(csInUse)
 {
 }

 ~CWin32CriticalSection()
 {
 }

 __forceinline void EnterInUse()
 {
  EnterCriticalSection(&m_csInUse);
 }

 __forceinline void LeaveInUse()
 {
  LeaveCriticalSection(&m_csInUse);
 }


private:
 CRITICAL_SECTION& m_csInUse;
};

class CSingleWaitWin32CS
{
public:
 CSingleWaitWin32CS(CRITICAL_SECTION& csInUse):cs(csInUse)
 {
  cs.EnterInUse();
 }

 ~CSingleWaitWin32CS()
 {
  cs.LeaveInUse();
 }

 CWin32CriticalSection cs;
};

class CWin32CS
{
public:
 CWin32CS(CRITICAL_SECTION& csInUse):cs(csInUse)
 {

 }
 ~CWin32CS()
 {
 }
 void Lock()
 {
  cs.EnterInUse();
 }

 void UnLock()
 {
  cs.LeaveInUse();
 }

 CWin32CriticalSection cs;
};

 

 用法:

class CTest
{
public:

 void Init();
 void UnInit();
 void Do1();
 void Do2();
 CRITICAL_SECTION m_cs;
};

void CTest::Init()
{
 InitializeCriticalSection(&m_cs); 
}
void CTest::UnInit()
{
 DeleteCriticalSection(&m_cs);
}

void CTest::Do1()
{
 CSingleWaitWin32CS cs1(m_cs);
 //do some thing
 ....
 ....
 ....
 ....
}

void CTest::Do2()
{
 CWin32CS  cs2(m_cs);
 cs2.Lock();
 //do some thing
 ....
 ....
 ....
 ....
 cs2.UnLock();
}

阅读更多
文章标签: class
个人分类: C/C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭