「在程序中,有三個線程,它們按照日程安排順序按照 運行。什麼是控制檯輸出?」C++多線程 - 輸出代碼
附表訂單 - 線程句柄
- 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;
}
早些時候氬你是問爲什麼異步(=亂序)執行不按順序發生? – Angew
你預計會發生什麼? –