Using Critical Section Objects

The following example shows how a thread initializes, enters, and leaves a critical section. As with the mutex example (see Using Mutex Objects), this example uses the try-finally structured exception-handling syntax to ensure that the thread calls the LeaveCriticalSection function to release its ownership of the critical section object.

CRITICAL_SECTION GlobalCriticalSection; 

// Initialize the critical section.
InitializeCriticalSection(&GlobalCriticalSection); 

// Request ownership of the critical section.
try 
{
    EnterCriticalSection(&GlobalCriticalSection); 
    // Access the shared resource.
}
finally 
{
    // Release ownership of the critical section.
    LeaveCriticalSection(&GlobalCriticalSection);
}