philosopher.c

来自「五个哲学家的就餐问题」· C语言 代码 · 共 63 行

C
63
字号
#include "apue.h"#include "lock.c"#define	 N	5static char *forks[5]={"fork0","fork1","fork2","fork3","fork4"};static int  time;void thinking(int k,int nsecs){	printf("philosopher %d is thinking\n",k);	sleep(nsecs);}void eating(int k,int nsecs){	printf("philosopher %d is eating\n",k);	sleep(nsecs);}void takefork(int k){	if(k==N-1){		lock(forks[0]);		lock(forks[k]);	}	else{		lock(forks[k]);		lock(forks[k+1]);	}}void putfork(int k){	if(k==N-1){		unlock(forks[0]);		unlock(forks[k]);	}	else{		unlock(forks[k]);		unlock(forks[k+1]);	}}void philosopher(int i){	while(1){		thinking(i,time);		takefork(i);		eating(i,time);		putfork(i);	}}int main(int argc,char *argv[]){	int 	i;	pid_t	pid;	if(argc==3 && !strcmp(argv[1],"-t"))	time=atoi(argv[2]);	else if(argc==1)	time=2;	else	err_sys("usage:philosopher [-t <time>]\n");	for(i=0;i<N;i++)	initlock(forks[i]);	for(i=0;i<N;i++){		if((pid=fork())<0)			err_sys("fork error!");		else if(!pid)			philosopher(i);	}	wait(NULL);	return 0;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?