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 <iostream>
#include <fstream>
#include <windows.h>
#include <vector>
#include <mutex>
using namespace std;
//bool *forks = NULL ;
bool forks[5]={true,true,true,true,true};
//mutex m;
DWORD WINAPI T_Philo(LPVOID lpParam)
{
int n;
n=*((int*)lpParam);
cout<<"Philo "<<n+1<<" is thinking."<<endl;
Sleep(500);
while (forks[n]==false || forks[(n+1)%5]==false){
}
if (forks[n]==true && forks[(n+1)%5]==true){
forks[n]=false;
forks[(n+1)%5]=false;
cout<<"Philo "<<n+1<<" is eating. "<<endl;
Sleep(200);
forks[n]=true;
forks[(n+1)%5]=true;
}
return 0;
}
int main()
{
HANDLE th[5];
DWORD threadID[5];
for (int i=0;i<5;i++){
th[i]=CreateThread(NULL,0,T_Philo[i],(LPVOID)i,0,&threadID[i]);
WaitForSingleObject(th[i],INFINITE);
}
} |
Partager