Critical Section Objects

A critical section object is a synchronization object that provides synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process. Like a mutex object, a critical section object can be owned by only one thread at a time, which makes it useful for protecting a shared resource from simultaneous access. There is no guarantee about the order in which threads obtain ownership of the critical section; however, Windows CE processes all threads equally.

A process is responsible for allocating the memory used by a critical section. Typically, this is done by declaring a variable of the type CRITICAL_SECTION. Before the threads of the process can use it, you must initialize the critical section by using the InitializeCriticalSection function.

A thread uses EnterCriticalSection to request ownership of a critical section and it uses the LeaveCriticalSection function to release ownership. If the critical section object is currently owned by another thread, EnterCriticalSection waits indefinitely for ownership. In contrast, when a mutex object is used for mutual exclusion, the wait functions accept a specified time-out interval.

Once a thread owns a critical section, it can make additional calls to EnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. To release its ownership, the thread must call LeaveCriticalSection once for each time that it entered the critical section.

Any thread of the process can use the DeleteCriticalSection function to release the system resources that were allocated when the critical section object was initialized. After this function has been called, the critical section object can no longer be used for synchronization.

When a critical section object is owned, the only other threads affected are those waiting for ownership in a call to EnterCriticalSection. Threads that are not waiting are free to continue running.

The following code example shows how a thread initializes, enters, and leaves a critical section. As with the mutex example described earlier, 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; 

InitializeCriticalSection(&GlobalCriticalSection); 

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