一、参考
二、代码
philo.cpp
#include<iostream>
#include<unistd.h>
#include<thread>
#include<mutex>
#include<stdlib.h>
std::mutex pmu[5];
void tfn(int i){
int left,right;
if(i == 4){
left = 0;
right = i;
}
else{
left = i;
right = i+1;
}
while(1)
{
sleep(1);
pmu[left].lock();
std::cout<<"thread "<<i<<" fetches "<<left<<std::endl;
if(pmu[right].try_lock()!= 0 )
{
pmu[left].unlock();
continue;
}
std::cout<<"thread "<<i<<" fetches "<<right<<std::endl;
std::cout<<"thread "<<i<<" is eating "<<std::endl;
sleep(2);
pmu[right].unlock();
std::cout<<"thread "<<i<<" release "<<right<<std::endl;
pmu[left].unlock();
std::cout<<"thread "<<i<<" release "<<left<<std::endl;
}
}
int main(int argc,char* argv[]){
std::thread w0(tfn,0);
std::thread w1(tfn,1);
std::thread w2(tfn,2);
std::thread w3(tfn,3);
std::thread w4(tfn,4);
w0.join();
w1.join();
w2.join();
w3.join();
w4.join();
return 0;
}