📄 philosopher_th.c
字号:
#include "apue.h"#include <semaphore.h>static sem_t *forks;static int time,N;void thinking(int i,int nsecs){ printf("philosopher %d is thinking\n",i); sleep(nsecs);}void eating(int i,int nsecs){ printf("philosopher %d is eating\n",i); sleep(nsecs);}void takefork(int i){ if(i==N-1){ sem_wait(&forks[0]); sem_wait(&forks[i]); } else{ sem_wait(&forks[i]); sem_wait(&forks[i+1]); }}void putfork(int i){ if(i==N-1){ sem_post(&forks[0]); sem_post(&forks[i]); } else{ sem_post(&forks[i]); sem_post(&forks[i+1]); }}void * philosopher(void *n){ int i; i=(int)n; while(1){ thinking(i,time); takefork(i); eating(i,time); putfork(i); }}int main(int argc,char *argv[]){ int i,status; pthread_t tpid; if(argc==2) time=2; else if(argc==4 && !strcmp(argv[2],"-t")) time=atoi(argv[3]); else err_sys("usage:philosopher_th <N> [-t <time>]\n"); N=atoi(argv[1]); forks=(sem_t*)malloc(N*sizeof(sem_t)); for(i=0;i<N;i++) sem_init(forks+i,0,1); for(i=0;i<N;i++){ status=pthread_create(&tpid,NULL,philosopher,(void *)i); if(status!=0) err_quit("can't creat thread:%s\n",strerror(status)); } pthread_join(tpid,NULL); return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -