CCriticalSection::Lock

Call this member function to gain access to the critical section object.

BOOL Lock( ); 
BOOL Lock( 
   DWORD dwTimeout  
);

Parameters

  • dwTimeout
    Lock ignores this parameter value.

Return Value

Nonzero if the function was successful; otherwise 0.

Remarks

Lock is a blocking call that will not return until the critical section object is signaled (becomes available).

If timed waits are necessary, you can use a CMutex object instead of a CCriticalSection object.

If Lock fails to allocate the necessary system memory, a memory exception (of type CMemoryException) is automatically thrown.

Example

This example demonstrates the nested critical section approach by controlling access to a shared resource (the static _strShared object) using a shared CCriticalSection object. The SomeMethod function demonstrates updating a shared resource in a safe manner.

//Definition of critical section class
class CMyCritSectClass
{
   static CString _strShared; //shared resource
   static CCriticalSection _critSect;
public:
   CMyCritSectClass(void) {}
   ~CMyCritSectClass(void) {}
   void SomeMethod(void); //locks, modifies, and unlocks shared resource
};

//Declaration of static members and SomeMethod
CString CMyCritSectClass::_strShared;
CCriticalSection CMyCritSectClass::_critSect;

void CMyCritSectClass::SomeMethod()
{
   _critSect.Lock();
   if (_strShared == "")
      _strShared = "<text>";
   _critSect.Unlock();
}

Requirements

Header: afxmt.h

See Also

Reference

CCriticalSection Class

Hierarchy Chart

CSingleLock::Lock