0

“程序中有三个线程,它们按照以下调度顺序运行。控制台输出是什么?”

计划订单 - 线程句柄

  • 1 h_thread1
  • 2 h_thread3
  • 3 h_thread3
  • 4 h_thread1
  • 5 h_thread1
  • 6 h_thread2
  • 7 h_thread2
  • 8 h_thread3
  • 9 h_thread3
  • 10 h_thread2

代码的输出是:玩家 1 吃东西:0 玩家 3 吃东西:0 玩家 2 吃东西:0

我不明白。我不明白整个过程。为什么第一行显示“玩家 1 吃东西:0”而第二行显示“玩家 3 吃东西:0”?这背后的逻辑是什么?你能解释一下这个过程吗?

#include <windows.h>
#include <iostream>
using namespace std; 
HANDLE forkMutexes[3]; 
DWORD WINAPI Player1(void* param){ 
for(int i =0; i < 3; i++){ //Computation Time : 2 Seconds
 WaitForSingleObject(forkMutexes[2],INFINITE); //Computation Time : 2 Seconds
 WaitForSingleObject(forkMutexes[0],INFINITE); //Computation Time : 1 Second
 cout << "Player 1 eating : " << i << endl; //Computation Time : 2 Seconds
 ReleaseMutex(forkMutexes[2]); //Computation Time : 1 Second
 ReleaseMutex(forkMutexes[0]); //Computation Time : 1 Second
 } 
return 0; 
} 
DWORD WINAPI Player2(void* param){ 
for(int i =0; i < 4; i++){ //Computation Time : 2 Seconds
 WaitForSingleObject(forkMutexes[0],INFINITE); //Computation Time : 1 Second
 WaitForSingleObject(forkMutexes[1],INFINITE); //Computation Time : 2 Seconds
 cout << "Player 2 eating : " << i << endl; //Computation Time : 2 Seconds
 ReleaseMutex(forkMutexes[0]); //Computation Time : 1 Second
 ReleaseMutex(forkMutexes[1]); //Computation Time : 1 Second
 } 
return 0; 
} 
DWORD WINAPI Player3(void* param){ 
for(int i =0; i < 1; i++){ //Computation Time : 2 Seconds
 WaitForSingleObject(forkMutexes[1],INFINITE); //Computation Time : 1 Second
 WaitForSingleObject(forkMutexes[2],INFINITE); //Computation Time : 1 Second
 cout << "Player 3 eating : " << i << endl; //Computation Time : 2 Seconds
 ReleaseMutex(forkMutexes[1]); //Computation Time : 2 Seconds
 ReleaseMutex(forkMutexes[2]); //Computation Time : 2 Seconds
 } 
return 0; 
} 
int main() 
{ 
 HANDLE h_thread1, h_thread2,h_thread3; 
int i_threadID1, i_threadID2, i_threadID3; 
for(int i =0; i <3 ; i++) 
 forkMutexes[i] = CreateMutex(NULL, FALSE, NULL); 
 h_thread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Player1, NULL, 
 0, (LPDWORD)&i_threadID1); 
 h_thread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Player2, NULL, 
 0, (LPDWORD)&i_threadID2); 
 h_thread3 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Player3, NULL, 
 0, (LPDWORD)&i_threadID3); 
 WaitForSingleObject(h_thread1,INFINITE); 
 WaitForSingleObject(h_thread2,INFINITE); 
 WaitForSingleObject(h_thread3,INFINITE); 
return 0; 
} 
4

2 回答 2

1

当您首先创建 thread1 时,播放器 1 是第一行。当 Player1 运行时,Player 2 正在等待 forkMutex0,而 player 3 正在等待 forkMutex2,因为 forkMutex1 没有被锁定,因为 player1 比 forkMutex0 更早释放 forkMutex2 播放器 3 将比播放器 2 更早打印

于 2013-05-25T11:52:04.030 回答
1

这是一个经典的多线程问题,请教哲学家:http ://en.wikipedia.org/wiki/Dining_philosophers_problem

Player1Player2并在由 .Player3创建的单独线程中运行CreateThread。线程的调度取决于操作系统,它们同时运行,确切的执行顺序基本上是未定义的。

于 2013-05-25T11:44:57.760 回答