1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include <windows.h>
#include <iostream>
HANDLE g_forks[5]={NULL, NULL, NULL, NULL, NULL};
DWORD WINAPI T_Philo(LPVOID lpParam)
{
int n = (int)(INT_PTR)lpParam;
std::cout<<"Philo "<<n+1<<" is thinking."<<std::endl;
Sleep(500);
//Note: Ceci est une méthode qui marche, parce que Windows résout le problème pour toi.
//Mais ce n'est pas le but de l'exercice: Le but de l'exercice,
//c'est de réussir à le faire sans t'empêtrer SANS utiliser WaitForMultipleObjects.
//Attempt to grab both forks simultaneously
HANDLE myForks[2] = { g_forks[n], g_forks[(n+1)%5] };
DWORD waited = WaitForMultipleObjects(2, myForks, TRUE, INFINITE);
if(waited == WAIT_OBJECT_0) {
std::cout<<"Philo "<<n+1<<" is eating. "<<std::endl;
Sleep(200);
ReleaseMutex(myForks[0]);
ReleaseMutex(myForks[1]);
}
//Aussi, est-ce normal que chaque philosophe ne mange qu'une seule fois? Normalement on fait ça en boucle
//(et comme condition d'arrêt, "ça fait dix minutes que le programme tourne" peut suffire)
return 0;
}
int main()
{
HANDLE th[5];
DWORD threadID[5];
//Create the forks
for (int i=0;i<5;i++) {
g_forks[i] = CreateMutex(NULL, FALSE, NULL);
}
//Spawn the philosophers
for (int i=0;i<5;i++) {
th[i]=CreateThread(NULL, 0, T_Philo, (LPVOID)(INT_PTR)i, 0, &threadID[i]);
}
//Wait for the end of the meal, clean up the dishes
for (int i=0;i<5;i++) {
WaitForSingleObject(th[i],INFINITE);
CloseHandle(th[i]), th[i]=NULL;
}
//Clean up the forks too.
for (int i=0;i<5;i++) {
CloseHandle(g_forks[i]), g_forks[i]=NULL;
}
return 0;
} |
Partager