Platform SDK: DLLs, Processes, and Threads

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 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);
}