# include<stdio.h>
# include<pthread.h>
# include<semaphore.h>
sem_t fork[100];
int n;
void *phil_job(int no)
{
printf("\nPhilosopher %d is thinking",no+1);
sem_wait(&fork[no]);
sem_wait(&fork[(no+1)%n]);
printf("\nPhilosopher %d started eating",no+1);
sleep(1);
printf("\nPhilosopher %d finished eating",no+1);
sem_post(&fork[(no+1)%n]);
sem_post(&fork[no]);
}
void main()
{
int i;
pthread_t phil_thread[100];
printf("\nEnter the number of philosopher :");
scanf("%d",&n);
for(i=0;i<n;++i)
if(sem_init(&fork[i],0,1)==-1)
{
perror("semaphore initialization failed");
exit(1);
}
for(i=0;i<n;++i)
{
if(pthread_create(&phil_thread[i],NULL,phil_job,(int*) i)!=0)
{
perror("semaphore creation failed");
exit(1);
}
}
for(i=0;i<n;++i)
if(pthread_join(phil_thread[i],NULL)!=0)
{
perror("semaphore join failed");
exit(1);
}
printf("\n \n thread join succesfull\n");
for(i=0;i<n;++i)
if(sem_destroy(&fork[i])==-1)
{
perror("semaphore destruction failed");
exit(1);
}
}
OUTPUT:
Enter the number of philosopher :5
Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 1 started eating
Philosopher 4 is thinking
Philosopher 4 started eating
Philosopher 3 is thinking
Philosopher 5 is thinking
Philosopher 4 finished eating
Philosopher 1 finished eating
Philosopher 3 started eating
Philosopher 5 started eating
Philosopher 3 finished eating
Philosopher 2 started eating
Philosopher 5 finished eating
Philosopher 2 finished eating
thread join succesfull
# include<pthread.h>
# include<semaphore.h>
sem_t fork[100];
int n;
void *phil_job(int no)
{
printf("\nPhilosopher %d is thinking",no+1);
sem_wait(&fork[no]);
sem_wait(&fork[(no+1)%n]);
printf("\nPhilosopher %d started eating",no+1);
sleep(1);
printf("\nPhilosopher %d finished eating",no+1);
sem_post(&fork[(no+1)%n]);
sem_post(&fork[no]);
}
void main()
{
int i;
pthread_t phil_thread[100];
printf("\nEnter the number of philosopher :");
scanf("%d",&n);
for(i=0;i<n;++i)
if(sem_init(&fork[i],0,1)==-1)
{
perror("semaphore initialization failed");
exit(1);
}
for(i=0;i<n;++i)
{
if(pthread_create(&phil_thread[i],NULL,phil_job,(int*) i)!=0)
{
perror("semaphore creation failed");
exit(1);
}
}
for(i=0;i<n;++i)
if(pthread_join(phil_thread[i],NULL)!=0)
{
perror("semaphore join failed");
exit(1);
}
printf("\n \n thread join succesfull\n");
for(i=0;i<n;++i)
if(sem_destroy(&fork[i])==-1)
{
perror("semaphore destruction failed");
exit(1);
}
}
OUTPUT:
Enter the number of philosopher :5
Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 1 started eating
Philosopher 4 is thinking
Philosopher 4 started eating
Philosopher 3 is thinking
Philosopher 5 is thinking
Philosopher 4 finished eating
Philosopher 1 finished eating
Philosopher 3 started eating
Philosopher 5 started eating
Philosopher 3 finished eating
Philosopher 2 started eating
Philosopher 5 finished eating
Philosopher 2 finished eating
thread join succesfull
No comments:
Post a Comment