#include <stdio.h>
#include <Windows.h>
#include<process.h>
int turn = 0;//全局的转换变量turn
CRITICAL_SECTION g_cs;//创建了一个临界区
DWORD WINAPI Fun(LPVOID lpParamter)//线程0
{
while (true) {
while (turn != 0);//等待turn等于0
EnterCriticalSection(& g_cs);//进入临界区
printf("0进程turn:");
turn = 1;//转换turn值
printf("%d\n",turn);
LeaveCriticalSection(&g_cs);//离开临界区
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParamter)//线程1
{
while (true) {
while (turn != 1); //等待turn等于1
EnterCriticalSection(&g_cs);//进入临界区
printf("1进程turn:");
turn = 0;//转换turn值
printf("%d\n", turn);
LeaveCriticalSection(&g_cs);//离开临界区
}
return 0;
}
int main() {
InitializeCriticalSection(&g_cs);//初始化临界区
HANDLE hThread;
HANDLE hThread2;
hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);//开始两个线程
Sleep(1000);//等待线程有充足的反应时间,或者其他方式控制线程的停止,运行时间不能过短
CloseHandle(hThread);
CloseHandle(hThread2);//关闭线程
}
严格轮换法
1 介绍
严格轮换法同样也是针对一个临界区设置一个变量,假设为Turn。以两个进程为例子:
- 当Turn为0时,Process 0才能能进入临界区,否则等待。等Process 0离开临界区后,将Turn设置为1.
- 当Turn为1时,Process 1才能进入临界区,否则等待。等Process 1离开临界区后,将Turn设置为0.
2 算法表示
- 当turn!=0时一直等待
- turn==0时进入临界区域
- 离开临界区域后turn设置为1