philosopher_th.c

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

C
64
字号
#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 + =
减小字号Ctrl + -
显示快捷键?