哲学家就餐问题(整理)的几个总结WaitForSingleObject(mutex, INFINITE);
cout << "philosopher " << myid << " begin......" << endl;
ReleaseMutex(mutex);
//初始状态为THINKING
mystate = THINKING;
leftFork = (myid) % PHILOSOPHER_NUM;
rightFork = (myid + 1) % PHILOSOPHER_NUM;
while (true)
{
switch(mystate)
{
case THINKING:
// 改变状态
mystate = HUNGRY;
strcpy(stateStr, "HUNGRY");
break;
case HUNGRY:
strcpy(stateStr, "HUNGRY");
// 先检查左筷子是否可用
ret = WaitForSingleObject(semaphore[leftFork], 0);
if (ret == WAIT_OBJECT_0)
{
//左筷子可用就拿起,再检查右筷子是否可用
ret = WaitForSingleObject(semaphore[rightFork], 0);
}
break;
case DINING:
// 吃完后把两支筷子都放下
ReleaseSemaphore(semaphore[leftFork], 1, NULL);
ReleaseSemaphore(semaphore[rightFork], 1, NULL);
// 改变自己的状态
mystate = THINKING;
strcpy(stateStr, "THINKING");
break;
}
// 输出状态
WaitForSingleObject(mutex, INFINITE);
cout << "philosopher " << myid << " is : " << stateStr << endl;
ReleaseMutex(mutex);
2022-04-22 19:12:42
1.57MB
哲学家
就餐
1