#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
int i = 0;
char name[5][2] = { "0","1","2","3","4" };
FILE* fpWrite = fopen("D:\\5.txt","w"); //D盘,5.txt存放日志
DWORD WINAPI philosopher(LPVOID lpParam) {
int id = i++;
int num;
HANDLE right, left;
if (id == 0) {
right = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, name[id]);
left = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, name[(id + 4) % 5]);
}
else {
left = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, name[id]);
right = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, name[(id + 4) % 5]);
}
while (1) {
srand((unsigned int)time(0));
num = rand()%400+100;
fprintf(fpWrite,"哲学家%d开始思考,将思考%dms\n", id, num);
Sleep(num);
num = rand()%400+100;
fprintf(fpWrite,"哲学家%d开始休息,将休息%dms\n", id, num);
Sleep(num);
WaitForSingleObject(left, INFINITE);
fprintf(fpWrite,"哲学家%d取了左手边的筷子\t%d\n", id, id);
WaitForSingleObject(right, INFINITE);
fprintf(fpWrite,"哲学家%d取了右手边的筷子\t%d\n", id, (id + 4) % 5);
num = rand() % 400 + 100-2;
fprintf(fpWrite,"哲学家%d开始吃饭,将吃饭%dms\n", id, num);
Sleep(num);
ReleaseSemaphore(left, 1, NULL);
fprintf(fpWrite,"哲学家%d放下左手边的筷子\t%d\n", id, id);
ReleaseSemaphore(right, 1, NULL);
fprintf(fpWrite,"哲学家%d放下右手边的筷子\t%d\n", id, (id + 4) % 5);
}
}
int main(void) {
HANDLE S[5];
HANDLE hThread[5];
for (int i = 0; i < 5; i++) {
S[i] = CreateSemaphore(NULL, 1, 1, name[i]);
}
for (int i = 0; i < 5; i++) {
hThread[i] = CreateThread(NULL, 0, philosopher, NULL, 0, NULL);
}
WaitForMultipleObjects(5, hThread, TRUE, 10000);
for (int i = 0; i < 5; i++) {
CloseHandle(S[i]);
}
fclose(fpWrite);
}
本文简单介绍了哲学家就餐问题,并进行了简单实现。
有任何问题都可以在评论区和我交流~~