我实际上有2个问题,这是第一个。
使用我在两个不同站点找到的代码,我编写了这两个关键部分包装类。
它会工作吗?
#ifndef CRITICALSECTION_H
#define CRITICALSECTION_H
#include "windows.h"
class CriticalSection{
long m_nLockCount;
long m_nThreadId;
typedef CRITICAL_SECTION cs;
cs m_tCS;
public:
CriticalSection(){
::InitializeCriticalSection(&m_tCS);
m_nLockCount = 0;
m_nThreadId = 0;
}
~CriticalSection(){ ::DeleteCriticalSection(&m_tCS); }
void Enter(){ ::EnterCriticalSection(&m_tCS); }
void Leave(){ ::LeaveCriticalSection(&m_tCS); }
void Try();
};
class LockSection{
CriticalSection* m_pCS;
public:
LockSection(CriticalSection* pCS){
m_pCS = pCS;
if(m_pCS)m_pCS->Enter();
}
~LockSection(){
if(m_pCS)m_pCS->Leave();
}
}
/*
Safe class basic structure;
class SafeObj
{
CriticalSection m_cs;
public:
void SafeMethod()
{
LockSection myLock(&m_cs);
//add code to implement the method ...
}
};
*/
#endif
还有第二个问题。在这里浏览时,我注意到作者没有包括
::初始化、删除、输入、离开临界区。这些不是班级正常工作所必需的吗?还是我错过了什么?