// Method 1: The critsect member variable in lock must be of the reference type.
Class critsect
{
Public:
Friend class lock;
Critsect () {initializecriticalsection (& _ critsection );}
~ Critsect () {deletecriticalsection (& _ critsection );}
PRIVATE:
Void acquire () {entercriticalsection (& _ critsection );}
Void release () {leavecriticalsection (& _ critsection );}
Critical_section _ critsection;
};
Class lock
{
Public:
Lock (critsect & critsect): _ critsect (critsect) {_ critsect. Acquire ();}
~ Lock () {_ critsect. Release ();}
PRIVATE:
Critsect & _ critsect;
};
//
// Method 2 is relatively simple and easy to understand
Class clock {
Public:
CLock () {InitializeCriticalSection (& m_criticalSection );}
Void Lock () {EnterCriticalSection (& m_criticalSection );}
Void Unlock () {LeaveCriticalSection (& m_criticalSection );}
Virtual ~ CLock () {DeleteCriticalSection (& m_criticalSection );}
Private:
CRITICAL_SECTION m_criticalSection;
};
//
Class CScopedLocker {
Public:
CScopedLocker (CLock * t): m_lock (t) {m_lock-> Lock ();}
~ CScopedLocker () {m_lock-> Unlock ();}
Private:
CLock * m_lock;
};
Note:
1 usage: Define an object with a class and call the function. As follows:
CritSect sect;
Lock lock (sect );
Or
CLock t;
Cscopedlocker ST (& T );
2. However, it seems that these two methods are not the most secure. For details, refer to Article 13 in Objective C ++: Object-based resource management. It is better.
Fangsh