0% found this document useful (0 votes)
17 views1 page

Philospher Code

The document contains C code that implements the dining philosophers problem using semaphores and threads. The code defines functions for philosophers to think, eat, take forks, and put forks back. It uses semaphores to synchronize access to forks and prevent deadlocks. Multiple philosopher threads are created to model the concurrent behavior.

Uploaded by

Atul Draws
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views1 page

Philospher Code

The document contains C code that implements the dining philosophers problem using semaphores and threads. The code defines functions for philosophers to think, eat, take forks, and put forks back. It uses semaphores to synchronize access to forks and prevent deadlocks. Multiple philosopher threads are created to model the concurrent behavior.

Uploaded by

Atul Draws
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

#include<stdio.

h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define LEFT (i+N-1)%N
#define RIGHT (i)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2
int state[N];
pthread_t t[N];
sem_t s[N];
sem_t mutex;

void think(int n){


printf("The philosopher %d is thinking\n",n);
sleep(1);
}
void eat(int n){
printf("\t\t\tThe philosopher %d is eating\n",n);
sleep(1);
printf("\t\t\tThe philosopher %d has finished eating\n",n);
}

void take_forks(int i){


sem_wait(&mutex);
state[i]=HUNGRY;
if(state[i]==HUNGRY&&state[LEFT]!=EATING&&state[RIGHT]!=EATING){
state[i]=EATING;
sem_wait(&s[LEFT]);
sem_wait(&s[RIGHT]);
}
sem_post(&mutex);
}

void put_forks(int i){


state[i]=THINKING;
sem_post(&s[LEFT]);
sem_post(&s[RIGHT]);
}
void *philo(int n){
while(1){
think(n);
take_forks(n);
if(state[n]==EATING){
eat(n);
put_forks(n);
}
}
}

void main(){
int i;
for(i=0;i<N;i++){
sem_init(&s[i],0,1);
}
sem_init(&mutex,0,1);
for(i=0;i<N;i++){
pthread_create(&t[i],0,(void *)philo,(void *)i);
}
while(1);
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy