⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 philosopher_th.c

📁 在unix下实验五
💻 C
字号:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
#include<signal.h>
#include<unistd.h>
#include<semaphore.h>

static sem_t* forks;
static int N;
static unsigned int nsecs;
void thinking(int i,unsigned int time)
{
	printf("philosopher %d is thinking.\n",i);
	sleep(time);
}
void eating(int i,unsigned int time)
{
	printf("philosopher %d is eating.\n",i);
	sleep(time);
}
void takeFork(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(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 = (int) n;
	while(1) {
		thinking(i, nsecs);	
		takeFork(i);			
		eating(i, nsecs);		
		putFork(i);			
	}
}
int main(int argc,char* argv[])
{
	int i,N,status;
	nsecs=2;
	pthread_t tpid;
	if(argc==2)
	{
		N=atoi(argv[1]);
	}
	else if(argc==4)
	{
		N=atoi(argv[1]);
		if(strcmp(argv[2],"-t")==0)
		{
			nsecs=atoi(argv[3]);
		}
		else
		{
			printf("Usage:philosopher_th   <N> [ -t  <time> ]\n");exit(0);
		}
	}
	else
	{
		printf("Usage:philosopher_th   <N> [ -t  <time> ]\n");exit(0);
	}
	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 )
	{
		printf("thread create error,no:%d",status);exit(0);
	}
	}
	pthread_join(tpid,NULL);
}


⌨️ 快捷键说明

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