编程语言

img xiangsl

一个线程同步类

发表于2004/12/30 15:53:00  681人阅读

// LockObj.h: interface for the CLockObj class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(LOCKOBJ_H)
#define LOCKOBJ_H

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "stdtype.h"

class CLockObj
{
public:
 virtual void Lock() = 0;
 virtual void Unlock() = 0;
};

class CLockObjCS: public CLockObj
{
protected:
 CRITICAL_SECTION m_cs;
public:
 CLockObjCS(){
  InitializeCriticalSection(&m_cs);
 };

 CLockObjCS(const CLockObjCS& ){
  InitializeCriticalSection(&m_cs);
 };

 CLockObjCS(const CLockObjCS* ){
  InitializeCriticalSection(&m_cs);
 };

 virtual ~CLockObjCS(){
  DeleteCriticalSection(&m_cs);
 };
 virtual void Lock(){
  EnterCriticalSection(&m_cs);
 };

 virtual void Unlock(){
  LeaveCriticalSection(&m_cs);
 };
};

class CLock
{
protected:
 CLockObj* m_pLockObj;
public:
 CLock(CLockObj *pLockObj):m_pLockObj(pLockObj){
  m_pLockObj->Lock();
 };

 virtual ~CLock( ){
  m_pLockObj->Unlock();
 }
};

#endif

使用方法
CLockObjCS g_mycs;
int g_iCount=0;
ThreadAdd()
{
  CLock lock(&g_mycs);
  ++g_iCount;
}

TheadDec()
{
  CLock lock(&g_mycs);
  --g_iCount;
}

阅读全文
0 0

相关文章推荐

img
取 消
img