模擬電影院多廳放映,使用 WaitForMultipleObjects 等待 3 個放映廳 Mutex。運行一段時間後返回 87(即 WAIT_ABANDONED_0 + 1),導致程序異常退出。
Mutex 擁有者線程意外終止且未釋放 Mutex。 具體場景:
Count[i] == 0 時才釋放 HallMutex[MAP[i]]。WaitForMultipleObjects 等待 3 個廳 Mutex 時,檢測到 HallMutex[1] 狀態為 WAIT_ABANDONED,返回 87。DWORD index = WaitForMultipleObjects(3, HallMutex, FALSE, -1);
if (index == WAIT_OBJECT_0 || index == WAIT_OBJECT_0+1 || index == WAIT_OBJECT_0+2) {
// 正常獲得
} else {
ExitProcess(GetLastError()); // 遇到 ABANDONED 直接退出
}
在等待循環中檢測 WAIT_ABANDONED 並重試,而非直接退出:
DWORD index = 0;
bool done = false;
do {
index = WaitForMultipleObjects(3, HallMutex, FALSE, -1);
if (index >= WAIT_OBJECT_0 && index < WAIT_OBJECT_0 + 3) {
MAP[i] = index - WAIT_OBJECT_0;
// ... 正常邏輯
done = true;
} else if (index >= WAIT_ABANDONED_0 && index < WAIT_ABANDONED_0 + 3) {
// Mutex 被遺棄,視為可用,重新等待
Sleep(0); // 讓出時間片
} else if (index == WAIT_FAILED) {
int e = GetLastError();
printf("WaitForMultipleObjects failed: %d\n", e);
ExitProcess(e);
}
} while (!done);
見原帖最佳回答,已將 do-while 迴圈包裹等待邏輯,忽略 WAIT_ABANDONED 並重試。
std::mutex + std::condition_variable (C++11) 替代原生 API,RAII 自動管理釋放。