1. 程式人生 > >死鎖之五個哲學家就餐問題 C語言實現

死鎖之五個哲學家就餐問題 C語言實現

#include<stdio.h>
#include<process.h>
#include<windows.h>
#include<stdlib.h>
#include<math.h>
HANDLE Mutext[5];
int chopstick = 0;
int *Physical;
unsigned int _stdcall ThreadFun(void *p)
{
int* current = (int*)p;
while (1)
{
if (abs(*current - chopstick)<4)
{
WaitForSingleObject(Mutext[*current], INFINITE);//加鎖
WaitForSingleObject(Mutext[(*current + 1) % 5], INFINITE);
printf("哲學家%d正在就餐...\n", *current);
printf("哲學家放下左邊%d筷子\n", chopstick);
chopstick = (chopstick + 1) % 5;
printf("哲學家放下右邊%d筷子\n\n", chopstick);
Sleep(2000);
ReleaseMutex(Mutext[(*current + 1) % 5]);//解鎖
ReleaseMutex(Mutext[(*current) % 5]);
}
}
return 0;
}
int main()
{
//初始化互斥變數,初始化要傳遞給執行緒的陣列
//HANDLE型別可以為(Event,Mutex,Process,Thread,Semaphore)陣列
int Physical[5];
int i;
for (i = 0; i<5; i++)
{
Mutext[i] = CreateMutexA(NULL, false, NULL);//建立了一個一個匿名的互斥鎖建立後
Physical[i] = i;
}
//然後開始進行建立執行緒
HANDLE *hThread = NULL;
hThread = new HANDLE[5];
for (i = 0; i<5; i++)
{
hThread[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, &Physical[i], 0, NULL);
}
WaitForMultipleObjects(5, hThread, true, INFINITE);//第二個引數為指定物件控制代碼組合中的第一個元素
for (i = 0; i<5; i++)
{
CloseHandle(hThread[i]);//銷燬建立的程序
CloseHandle(Mutext[i]);//銷燬鎖
}
return 0;
}