2019独角兽企业重金招聘Python工程师标准>>>
#include
#include
#include
#include
#include
#include
pthread_t hThread[5];
int cs[5];
int mark;
void philosopher(int n) {
while(mark) {}
long long int seed;
seed = time(NULL);
while(1) {
int state = 0;
seed++;
srand(seed);
state = rand()%2;
if(state == 1) {
printf("%d号哲学家决定吃饭\n",n+1);
} else {
printf("%d号哲学家决定思考\n",n+1);
}
int dirct;
int times;
seed++;
srand(seed);
times = rand()%10;
int mark1,mark2;
mark1 = 0;
mark2 = 0;
if(state == 1) {
while(1) {
if(cs[n] == 0) {
cs[n] = 1;
mark1 = 1;
printf("%d号哲学家拿起了左边的%d号筷子\n",n+1,n+1);
break;
}
if(times == 0) {
break;
}
usleep(1);
times = times - 1;
if(times == 0) {
break;
}
}
while(1) {
if(cs[(n+1)%5] == 0) {
cs[(n+1)%5] = 1;
mark2 = 1;
printf("%d号哲学家拿起了右边的%d号筷子\n",n+1,(n+1)%5+1);
break;
}
if(times == 0) {
break;
}
usleep(1);
times = times - 1;
if(times == 0) {
break;
}
}
if(mark1 == 1 && mark2 == 1) {
printf("%d号哲学家开始吃饭\n",n+1);
}
} else {
printf("%d号哲学家开始思考\n",n+1);
}
usleep(times);
if(state == 1) {
if(mark1 == 1 && mark2 == 1) {
printf("%d号哲学家吃饭结束\n",n+1);
}
if(mark1 == 1) {
printf("%d号哲学家放下了左边的%d号筷子\n",n+1,n+1);
cs[n] = 0;
mark1 = 0;
}
if(mark2 == 1) {
printf("%d号哲学家放下了右边的%d号筷子\n",n+1,(n+1)%5+1);
cs[(n+1)%5] = 0;
mark2 = 0;
}
} else {
printf("%d号哲学家思考结束\n",n+1);
}
}
}
int main(int argc,char *argv[]) {
struct timeval tpstart,tpend;
mark = 1;
gettimeofday(&tpstart,NULL);
int i;
for(i = 0; i < 5; i++) {
cs[i] = 0;
}
for(i = 0; i < 5; i++) {
pthread_create(&hThread[i],NULL,(void*)philosopher,i);
}
mark = 0;
sleep(50);
for(i = 0; i < 5; i++) {
pthread_cancel(hThread[i]);
}
return 0;
}