0% found this document useful (0 votes)
14 views3 pages

ASS5

n
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)
14 views3 pages

ASS5

n
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/ 3

ASSIGNMENT:-5

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM 5
sem_t chop[NUM];

void* philosopher(void *arg) {


int id = *(int*)arg;
for (int i = 0; i < 3; i++) {
printf("Philosopher %d is thinking!!\n", id);
sleep(1);
if (id % 2 == 0) {
sem_wait(&chop[id]);
sem_wait(&chop[(id + 1) % NUM]);
} else {
sem_wait(&chop[(id + 1) % NUM]);
sem_wait(&chop[id]);
}
printf("philosopher %d is hungry.\n",id);
printf("Philosopher %d takes fork %d and %d\n",id,id+1,id);
printf("Philosopher %d is eating.\n", id);
sem_post(&chop[id]);
sem_post(&chop[(id + 1) % NUM]);
printf("Philosopher %d is done eating\n", id);
}
return NULL;
}

int main() {
pthread_t philosophers[NUM];
int id[NUM];

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

sem_init(&chop[i], 0, 1);

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

id[i] = i;

pthread_create(&philosophers[i], NULL, philosopher, (void*)&id[i]);

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

pthread_join(philosophers[i], NULL);

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

sem_destroy(&chop[i]);

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