Critical Sections
Overview
A critical section is a synchronization primitive that provides mutual exclusion for threads within the same process. It is faster than a mutex because it does not require kernel transitions unless contention occurs.
Syntax
typedef struct _CRITICAL_SECTION {
void *DebugInfo;
long LockCount;
long RecursionCount;
void *OwningThread;
void *LockSemaphore;
unsigned long SpinCount;
} CRITICAL_SECTION, *LPCRITICAL_SECTION;
Functions
InitializeCriticalSection
EnterCriticalSection
LeaveCriticalSection
DeleteCriticalSection
Initializes a critical section object.
VOID InitializeCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);
Waits for ownership of the critical section.
VOID EnterCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);
Releases ownership.
VOID LeaveCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);
Deletes the critical section object.
VOID DeleteCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);
Parameters
- lpCriticalSection – Pointer to the CRITICAL_SECTION structure to be initialized, entered, or deleted.
Remarks
- Critical sections are only usable within a single process. For inter-process synchronization, use a Mutex.
- The system may spin on a critical section a few times before falling back to a kernel wait, which improves performance on low-contention scenarios.
- Always pair each
EnterCriticalSectionwith a matchingLeaveCriticalSectionto avoid deadlocks.
Example
#include <windows.h>
#include <stdio.h>
CRITICAL_SECTION cs;
DWORD WINAPI ThreadProc(LPVOID param) {
for (int i = 0; i < 5; ++i) {
EnterCriticalSection(&cs);
printf("Thread %d - iteration %d\n", GetCurrentThreadId(), i);
LeaveCriticalSection(&cs);
Sleep(10);
}
return 0;
}
int main(void) {
InitializeCriticalSection(&cs);
HANDLE h1 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
HANDLE h2 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
WaitForSingleObject(h1, INFINITE);
WaitForSingleObject(h2, INFINITE);
DeleteCriticalSection(&cs);
return 0;
}
Comments