#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