Kernel Synchronization Overview
Windows kernel provides a rich set of synchronization primitives that enable safe access to shared resources across threads and processes. Choose the appropriate primitive based on performance, scope, and ownership requirements.
Common Primitives
- Mutex – owned by a thread, can be used across processes.
- Semaphore – permits a fixed number of concurrent accesses.
- Event – signals one or more waiting threads.
- Critical Section – fast intra-process lock.
- SRWLock – lightweight shared/exclusive lock.
- Condition Variable – used with SRWLock or Critical Section for wait/signaling patterns.
Example: Using a Mutex
#include <windows.h>
HANDLE g_hMutex;
DWORD WINAPI ThreadFunc(LPVOID lpParam){
WaitForSingleObject(g_hMutex, INFINITE);
// Critical section
Sleep(100);
ReleaseMutex(g_hMutex);
return 0;
}
int main(){
g_hMutex = CreateMutex(NULL, FALSE, NULL);
HANDLE hThreads[2];
for(int i=0;i<2;i++) hThreads[i]=CreateThread(NULL,0,ThreadFunc,NULL,0,NULL);
WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);
CloseHandle(g_hMutex);
return 0;
}