CriticalSection
以原子方式访问。在执行之前独占对一些共享资源的访问权。
-头文件:
Windoes.h
process.h
-定义:
CRITICAL_SECTION cs;
-初始化:
VOID InitializeCriticalSection(&cs);
-删除:
VOID DeleteCriticalSection(&cs);
-进入关键段
VOID EnterCriticalSection(&cs);
BOOL TryEnterCriticalSection(&cs);//这个函数不会等待,如果进不去,就继续向下执行
-离开关键段
VOID LeaveCriticalSection(&cs);
一个小例子
借还书
main函数调用,启动
void OnActive()
{
HANDLE hThreadRead;
HANDLE hThreadWrite;
DWORD dwThreadIDRead,deThreadIDWrite;
hThreadRead = (HANDLE)_beginthreadex(NULL,0,ThreadFuncRead,NULL,0,(unsigned int*)&dwThreadIDRead);
hThreadWrite = (HANDLE)_beginthreadex(NULL,0,ThreadFuncWrite,NULL,0,(unsigned int *)&deThreadIDWrite);
InitializeCriticalSection(&cs);
Sleep(1000);
CloseHandle(hThreadRead);
CloseHandle(hThreadWrite);
DeleteCriticalSection(&cs);
}
借书操作
int bookNumbers = 10;
CRITICAL_SECTION cs;
unsigned __stdcall ThreadFuncRead(void*)
{
while(1)
//for(int i = 0;i<10;i++)
{
EnterCriticalSection(&cs);
if (bookNumbers>0)
{
printf("借走一本书,剩余数量:%d\n",--bookNumbers);
LeaveCriticalSection(&cs);
}
else
{
LeaveCriticalSection(&cs);
break;
}
}
return 1;
}
还书操作
unsigned __stdcall ThreadFuncWrite(void*)
{
while(1)
//for(int i = 0;i<10;i++)
{
EnterCriticalSection(&cs);
if (bookNumbers<10)
{
printf("还回一本书,剩余数量:%d\n",++bookNumbers);
LeaveCriticalSection(&cs);
}
else
{
LeaveCriticalSection(&cs);
break;
}
}
return 1;
}
网友评论