#include <stdio.h>
#include <windows.h>
typedef RTL_CRITICAL_SECTION CRITICAL_SECTION;
CRITICAL_SECTION g_cs; //声明关键段
// 共享资源
char g_cArray[10];
unsigned int g_Count = 0;
DWORD WINAPI ThreadProc10(LPVOID pParam)
{
// 进入临界区
EnterCriticalSection(&g_cs);
// 对共享资源进行写入操作
for (int i = 0; i < 10; i++)
{
g_Count++;
printf("g_Count is %d\n", g_Count);
Sleep(1);
}
// 离开临界区
LeaveCriticalSection(&g_cs);
return 0;
}
DWORD WINAPI ThreadProc11(LPVOID pParam)
{
// 进入临界区
EnterCriticalSection(&g_cs);
// 对共享资源进行写入操作
for (int i = 0; i < 10; i++)
{
g_Count--;
printf("g_Count is %d\n", g_Count);
Sleep(1);
}
// 离开临界区
LeaveCriticalSection(&g_cs);
return 0;
}
int main()
{
// 初始化临界区
InitializeCriticalSection(&g_cs);
// 启动线程
HANDLE ThreadProcHand10 = CreateThread(NULL, 0, ThreadProc10, 0, 0, NULL); // 创建线程
HANDLE ThreadProcHand11 = CreateThread(NULL, 0, ThreadProc11, 0, 0, NULL); // 创建线程
// 等待计算完毕
Sleep(300);
return 0;
}
输出:
线程中,屏蔽掉 EnterCriticalSection(&g_cs)和LeaveCriticalSection(&g_cs) 将打印如下: