A CRITICAL_SECTION for Protecting Shared Variables
Using CRITICAL_SECTIONs is simple, and one common use is to allow threads to access global shared variables. For example, consider a threaded server (as in Figure 7-1) in which there might be a need to maintain usage statistics such as:
- The total number of requests received
- The total number of responses sent
- The number of requests currently being processed by server threads
Because the count variables are global to the process, two threads must not modify the counts simultaneously. CRITICAL_SECTION objects provide one means of ensuring this, as shown by the code sequence below and in Program 8-1, much simpler than the server system, illustrates this CRITICAL_SECTION usage.
Figure 8-2. Synchronized Threads Sharing Memory

CRITICAL_SECTION cs1;
volatile DWORD N = 0, M;
/* N is a global variable, shared by all threads. */
InitializeCriticalSection (&cs1);
...
EnterCriticalSection (&cs1);
if (N < N_MAX) { M = N; M += 1; N = M; }
LeaveCriticalSection (&cs1);
...
DeleteCriticalSection (&cs1);
Figure 8-1 example and illustrates how CSs can solve synchronization problems.