// CriticalSection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include "conio.h"
//定义一个临界区值
CRITICAL_SECTION g_cs={0};
void Print(){
//进入临界区 相当于加锁 当线程1在打印了 线程2来了 g_cs的标识没有所以就停留在这里
EnterCriticalSection(&g_cs);
printf("long long long....\n");
//离开临界区 相当于解锁 当线程1打印好了 g_cs 就会发生改变 让线程2进程 就这样进行反复
//临界区 锁定了这一块模块 其他线程进不来 起了这样的作用
LeaveCriticalSection(&g_cs);
}
DWORD WINAPI PrintProcls(LPVOID pParam){
while(1){
Print();
Sleep(1000);
}
return 0;
}
//CriticalSection
void CreateThd(){
DWORD tID=0;
HANDLE hThread[2]={0};
hThread[0]=CreateThread(NULL,0,PrintProcls,NULL,0,&tID);
hThread[1]=CreateThread(NULL,0,PrintProcls,NULL,0,&tID);
getch();
}
int main(int argc, char* argv[])
{
//初始化临界区
InitializeCriticalSection(&g_cs);
CreateThd();
DeleteCriticalSection(&g_cs);
return 0;
}