#include <iostream>
#include <windows.h>
using namespace std; CRITICAL_SECTION cs; // LockCount 它被初始化为数值 -1,此数值等于或大于 0 时,表示此临界区被占用;等待获得临界区的线程数:LockCount - (RecursionCount -1)
// RecursionCount 此字段包含所有者线程已经获得该临界区的次数
// OwningThread 此字段包含当前占用此临界区的线程的线程标识符,此线程 ID 与GetCurrentThreadId 所返回的 ID 相同 DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{
for (int x = ; x < ; x++)
{
EnterCriticalSection(&cs);
Sleep();
printf("11111:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
LeaveCriticalSection(&cs);
}
return ;
} DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
for (int x = ; x < ; x++)
{
EnterCriticalSection(&cs);
Sleep();
printf("22222:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
LeaveCriticalSection(&cs);
}
return ;
} DWORD WINAPI ThreadProc3(LPVOID lpParameter)
{
for (int x = ; x < ; x++)
{
EnterCriticalSection(&cs);
Sleep();
printf("33333:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
LeaveCriticalSection(&cs);
}
return ;
} DWORD WINAPI ThreadProc4(LPVOID lpParameter)
{
for (int x = ; x < ; x++)
{
EnterCriticalSection(&cs);
Sleep();
printf("44444:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
LeaveCriticalSection(&cs);
}
return ;
} int main()
{
// 初始化临界区
InitializeCriticalSection(&cs);
// printf("%x %x %x", cs.LockCount, cs.RecursionCount, cs.OwningThread);
// 创建一个新的线程
HANDLE hTread1 = CreateThread(, , ThreadProc1, , , );
// 创建一个新的线程
HANDLE hTread2 = CreateThread(, , ThreadProc2, , , );
// 创建一个新的线程
HANDLE hTread3 = CreateThread(, , ThreadProc3, , , );
// 创建一个新的线程
HANDLE hTread4 = CreateThread(, , ThreadProc4, , , );
// 如果不在其它的地方引用它就关闭句柄
::CloseHandle(hTread1);
::CloseHandle(hTread2);
::CloseHandle(hTread3);
::CloseHandle(hTread4);
// 销毁临界区
// DeleteCriticalSection(&cs);
getchar();
return ;
}