0% found this document useful (0 votes)
5 views2 pages

Experiment No 11

The document presents an implementation of the Dining Philosopher problem using semaphores in C. It includes a program that simulates philosophers thinking and eating while managing fork resources to prevent deadlock. The main function initializes semaphores, creates philosopher threads, and cleans up resources after execution.

Uploaded by

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

Experiment No 11

The document presents an implementation of the Dining Philosopher problem using semaphores in C. It includes a program that simulates philosophers thinking and eating while managing fork resources to prevent deadlock. The main function initializes semaphores, creates philosopher threads, and cleans up resources after execution.

Uploaded by

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

EXPERIMENT NO-11

Aim: Implement the Dining Philospher problem using semaphores.


Program:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define N 5 // Number of philosophers

sem_t forks[N]; // Semaphores representing forks


sem_t mutex; // Semaphore to prevent deadlock

void *philosopher(void *arg) {


int id = *(int *)arg;

while (1) {
printf("Philosopher %d is thinking\n", id);
sleep(1);

// Pick up forks
sem_wait(&mutex); // Prevent deadlock
sem_wait(&forks[id]); // Pick left fork
sem_wait(&forks[(id + 1) % N]); // Pick right fork
sem_post(&mutex);

printf("Philosopher %d is eating\n", id);


sleep(2);

// Put down forks


sem_post(&forks[id]); // Release left fork
sem_post(&forks[(id + 1) % N]); // Release right fork

printf("Philosopher %d finished eating\n", id);


sleep(1);
}
}

int main() {
pthread_t philosophers[N];
int ids[N];

sem_init(&mutex, 0, 1);
for (int i = 0; i < N; i++)
sem_init(&forks[i], 0, 1);

for (int i = 0; i < N; i++) {


ids[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &ids[i]);
}

for (int i = 0; i < N; i++)


pthread_join(philosophers[i], NULL);

for (int i = 0; i < N; i++)


sem_destroy(&forks[i]);
sem_destroy(&mutex);

return 0;
}

Output:

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