试图通过创建一个门卫来解决哲学家就餐问题,只允许 4 位哲学家同时用餐,计划为此使用信号量,但网络上关于它们的资料有限,我不知道如何增加信号量的价值一旦发出信号。
#define INITIAL_COUNT 1
#define MAX_COUNT 4
主要的()
philo.doorSemaphore = CreateSemaphore(
NULL, //default security attributes
INITIAL_COUNT, //initial count
MAX_COUNT, //maximum count
NULL);
while (philo.not_dead == true)
{
int num_philosophers = 5;
for (int i = 0; i < 5; i++)
{
philo.mythread[i] = thread (philosophersFunction, i); //init 5 threads calling philofunction each loop
philo.mythread[i].join(); //join thread to current thread each loop
}
sleep_for(milliseconds(500));
system("cls");
}
等待()
void Philosophers::waiting(int current)
{
dWaitResult = WaitForSingleObject(doorSemaphore, 0L);
//waitResult = WaitForSingleObject(semaphores, 0L);
switch (dWaitResult)
{
case WAIT_OBJECT_0:
p[current] = hungry;
ReleaseSemaphore(doorSemaphore, 1, NULL);
break;
case WAIT_TIMEOUT:
hunger[current] ++;
counter[current] ++;
case WAIT_FAILED :
break;
CloseHandle(doorSemaphore);
}
}