dining philosophers problem solution using semaphores in c

/*
This code is contributed by :
Tanishq Vyas (github : https://github.com/tanishqvyas )

Use of Binary Semaphores has been made along with inversion of
last philosopher's order of picking chopsticks, in order to avoid
circular wait condition. Thus preventing deadlock.
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>  //Header file for sleep(). man 3 sleep for details. 
#include <pthread.h> 
#define NUM_PHILOSOPHERS 5


// Binary Semaphores to keep track of Philosopher
int chopsticks[NUM_PHILOSOPHERS];

// Functions for philosophers
void *philosopher_behaviour(void* id)
{   
    int philosopher_number = *((int*)id);

    // Endless loop for philosopher
    while(1)
    {
        // Thinking Section
        printf("PID : (%ld)  Philosopher %d is THINKING\n", pthread_self(), philosopher_number+1);
        sleep(1);
        
        // Hungry Section
        printf("PID : (%ld)  Philosopher %d is Hungry\n", pthread_self(), philosopher_number+1);

        // Philosopher khaan Paan section
        while(1)
        {
            // Entry Section : Check for Chopsticks Availability
            // Check n pick left chopstick
            if(chopsticks[philosopher_number] == 1)
                continue;            
            // check n pick right Chopstick
            if(chopsticks[(philosopher_number+1)%NUM_PHILOSOPHERS] == 1)
                continue;

            chopsticks[philosopher_number] = 1;
            chopsticks[(philosopher_number+1)%NUM_PHILOSOPHERS] = 1;

            printf("PID : (%ld)  Philosopher %d picks #%d and #%d chopsticks up\n", pthread_self(), philosopher_number+1, philosopher_number+1, 1 + ((philosopher_number+1)%NUM_PHILOSOPHERS));

            // Khao Noodles Pel kr k
            printf("PID : (%ld)  Philosopher %d is Eating Noodles\n", pthread_self(), philosopher_number+1);
            sleep(1);

            // EXIT Section : Free the Chopsticks
            chopsticks[philosopher_number] = 0;
            chopsticks[(philosopher_number+1)%NUM_PHILOSOPHERS] = 0;
            
            printf("PID : (%ld)  Philosopher %d puts #%d and #%d chopsticks down\n", pthread_self(), philosopher_number+1, philosopher_number+1, 1 + ((philosopher_number+1)%NUM_PHILOSOPHERS));
            break;
        }
    }
}

void *philosopher_behaviour_rev(void* id)
{
    int philosopher_number = *((int*)id);

    // Endless loop for philosopher
    while(1)
    {
        // Thinking Section
        printf("PID : (%ld)  Philosopher %d is THINKING\n", pthread_self(), philosopher_number+1);
        sleep(1);
        
        // Hungry Section
        printf("PID : (%ld)  Philosopher %d is Hungry\n", pthread_self(), philosopher_number+1);

        // Philosopher khaan Paan section
        while(1)
        {
            // Entry Section : Check for Chopsticks Availability

            // check n pick right Chopstick
            if(chopsticks[(philosopher_number+1)%NUM_PHILOSOPHERS] == 1)
                continue;

            // Check n pick left chopstick
            if(chopsticks[philosopher_number] == 1)
                continue;            
            
            chopsticks[(philosopher_number+1)%NUM_PHILOSOPHERS] = 1;
            chopsticks[philosopher_number] = 1;

            printf("PID : (%ld)  Philosopher %d picks #%d and #%d chopsticks up\n", pthread_self(), philosopher_number+1, philosopher_number+1, 1 + ((philosopher_number+1)%NUM_PHILOSOPHERS));

            // Khao Noodles Pel kr k
            printf("PID : (%ld)  Philosopher %d is Eating Noodles\n", pthread_self(), philosopher_number+1);
            sleep(1);

            // EXIT Section : Free the Chopsticks
            chopsticks[philosopher_number] = 0;
            chopsticks[(philosopher_number+1)%NUM_PHILOSOPHERS] = 0;
            
            printf("PID : (%ld)  Philosopher %d puts #%d and #%d chopsticks down\n", pthread_self(), philosopher_number+1, philosopher_number+1, 1 + ((philosopher_number+1)%NUM_PHILOSOPHERS));

            break;
        }
    }
}

int main(int argc, char const *argv[])
{
    // Declare thread array
    pthread_t thread_ids[NUM_PHILOSOPHERS];
    int philosopher_numbers[NUM_PHILOSOPHERS];
    
    // Setting the Philosopher Numbers
    for (int i = 0; i < NUM_PHILOSOPHERS; i++)
    {
        philosopher_numbers[i] = i;
    }

    // Setting the state of all Chopsticks as 0
    for (int i = 0; i < NUM_PHILOSOPHERS; i++)
    {
        chopsticks[i] = 0;
    }

    // Thread Creation
    for (int i = 0; i < NUM_PHILOSOPHERS-1; i++)
    {
        pthread_create(&thread_ids[i], NULL, philosopher_behaviour, (void*)&philosopher_numbers[i]); 
    }

    // Reversing the last philosopher to avoid cyclic wait
    pthread_create(&thread_ids[NUM_PHILOSOPHERS-1], NULL, philosopher_behaviour_rev,(void*) &philosopher_numbers[NUM_PHILOSOPHERS-1]); 

    // Wait equivalent
    for (int i = 0; i < NUM_PHILOSOPHERS; i++)
    {
        pthread_join(thread_ids[i], NULL); 
    }

    exit(0);
}

4
4
Awgiedawgie 440215 points

                                    #include&lt;stdio.h&gt;#include&lt;stdlib.h&gt;#include&lt;pthread.h&gt;#include&lt;semaphore.h&gt;#include&lt;unistd.h&gt;sem_t room;sem_t chopstick[5];void * philosopher(void *);void eat(int);int main(){	int i,a[5];	pthread_t tid[5];		sem_init(&amp;room,0,4);		for(i=0;i&lt;5;i++)		sem_init(&amp;chopstick[i],0,1);			for(i=0;i&lt;5;i++){		a[i]=i;		pthread_create(&amp;tid[i],NULL,philosopher,(void *)&amp;a[i]);	}	for(i=0;i&lt;5;i++)		pthread_join(tid[i],NULL);}void * philosopher(void * num){	int phil=*(int *)num;	sem_wait(&amp;room);	printf(&quot;\nPhilosopher %d has entered room&quot;,phil);	sem_wait(&amp;chopstick[phil]);	sem_wait(&amp;chopstick[(phil+1)%5]);	eat(phil);	sleep(2);	printf(&quot;\nPhilosopher %d has finished eating&quot;,phil);	sem_post(&amp;chopstick[(phil+1)%5]);	sem_post(&amp;chopstick[phil]);	sem_post(&amp;room);}void eat(int phil){	printf(&quot;\nPhilosopher %d is eating&quot;,phil);}/* BY - ANUSHKA DESHPANDE */

4 (4 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
Dining Philosophers problem using Semaphores c program for dining philosophers problem semaphore struct c program for dining philosophers problem using semaphores sem_init c program for dining philosophers problem using semaphores dining philosophers problem semaphore solution Develop a deadlock free semaphore based solution to dinning philosopher problem dining philosophers problem in operating system c # dining philosophers code dining philosophers problem code dining philosophers problem c++ create process 5 philosophers problem c dining philosophers problem pseudocode philosophers problem c dining philosophers cpp dining philosophers problem source code in c dining philosophers problem solution using semaphores inc dining philosophers problem solution using semaphores in c dining philosophers problem in c with critical section dining philosophers problem solution using semaphores dining philosopher in os Dining-Philosophers problem using Semaphores Describe the scenario in which Deadlock occurs in Dining Philosopher Problem. How can it be resolved using Semaphore? Explain with code. dining philosophers problem solution in c dining philosophers problem c++ code Write a program that simulates the philosophers using threads, and the resources (fork and sauce bowls) using a shared variable. how to solve dining philosophers problem solution step by step coding in c dining philosophers problem solution in c Write a C program to implement the solution to DiningPhilosophers problem philopsopher problem in c dining philosophers implementation in c dining philosophers code dining philosophers problem c code dining philosophers problem in c without deadlock dining philosophers problem code c dining philosophers problem using semaphores in c dining philosophers problem code in c different implementation of dining philosophers problem in c dining philosophers problem solution using semaphore in java dining philosophers problem in c
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source