Question

In: Computer Science

can someome investigate my program that utilizes semaphores that can result in deadlock due to programming...

can someome investigate my program that utilizes semaphores that can result in deadlock due to programming errors and help in finding out if the solution meet all criteria for the critical section
  • If yes, then comment code identifying the parts of code that do
  • If no, could you help in fixing the code wherever given solution fails criteria in the code below

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

#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N

int state[N];
int phil[N] = { 0, 1, 2, 3, 4 };

sem_t mutex;
sem_t S[N];

void test(int phnum)
{
if (state[phnum] == HUNGRY
&& state[LEFT] != EATING
&& state[RIGHT] != EATING) {
// state that eating
state[phnum] = EATING;

sleep(2);

printf("Philosopher %d takes fork %d and %d\n",
phnum + 1, LEFT + 1, phnum + 1);

printf("Philosopher %d is Eating\n", phnum + 1);

// sem_post(&S[phnum]) has no effect
// during takefork
// used to wake up hungry philosophers
// during putfork
sem_post(&S[phnum]);
}
}

// take up chopsticks
void take_fork(int phnum)
{

sem_wait(&mutex);

// state that hungry
state[phnum] = HUNGRY;

printf("Philosopher %d is Hungry\n", phnum + 1);

// eat if neighbours are not eating
test(phnum);

sem_post(&mutex);

// if unable to eat wait to be signalled
sem_wait(&S[phnum]);

sleep(1);
}

// put down chopsticks
void put_fork(int phnum)
{

sem_wait(&mutex);

// state that thinking
state[phnum] = THINKING;

printf("Philosopher %d putting fork %d and %d down\n",
phnum + 1, LEFT + 1, phnum + 1);
printf("Philosopher %d is thinking\n", phnum + 1);

test(LEFT);
test(RIGHT);

sem_post(&mutex);
}

void* philospher(void* num)
{

while (1) {

int* i = num;

sleep(1);

take_fork(*i);

sleep(0);

put_fork(*i);
}
}

int main()
{

int i;
pthread_t thread_id[N];

// initialize the semaphores
sem_init(&mutex, 0, 1);

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

sem_init(&S[i], 0, 0);

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

// create philosopher processes
pthread_create(&thread_id[i], NULL,
philospher, &phil[i]);

printf("Philosopher %d is thinking\n", i + 1);
}

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

pthread_join(thread_id[i], NULL);
}

Solutions

Expert Solution

Here only a slight change needed to be made to handle the case in which let's say suppose we have 4 philosopher and after each one of them picks their left fork then context switch occurs and we go to next philosopher. that is after philosopher-0 has picked the left fork of index 0 then context switch occurs and we go to philosopher-1 who also captures its left fork i.e. fork 1 and again context switch occurs so in this way switching occurs. so in the ned we will be currently at the philosopher-3 and he would pick its left fork i.e. fork-3 and look for the right fork i.e. fork-0 but this was already picked by the philosopher-0. So the system goes into the deadlock. Here to prevent this situation we just need to change the testing condition for the last philosopher such that he looks for the right fork and after that looks fo left fork. So if this was the case then philosopher-4 instead of picking the leftfork i.e. fork-3 first it will first look for fork-0 but since it is already picked by the philosopher-0 so it will stop. and now the philosopher-2 can continue with its process since fork-3 is still not picked. he puts back fork-2 after eating. So in this way after philosopher-2 , philosopher-1 woulad also complete the task and then philosopher-0. Now after this philosopher-3 can pick the right fork i.e. fork-0 and continue its. task.

void put_fork(int phnum)

{

sem_wait(&mutex);

// state that thinking

state[phnum] = THINKING;

printf("Philosopher %d putting fork %d and %d down\n",

phnum + 1, LEFT + 1, phnum + 1);

printf("Philosopher %d is thinking\n", phnum + 1);

if(phnum==N-1){ // this is the last philosopher for which we reverse the order of checking it will first check right then left

test(RIGHT);

test(LEFT);

}

else{ // this is for the remaining philosopher for which the order of checking will be first check left then right

test(LEFT);

test(RIGHT);

}

sem_post(&mutex);

}


Related Solutions

Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the program to add two more threads: add a class C and a class D, and call them from main.  Does deadlock occur? import java.util.concurrent.locks.*; class A implements Runnable {             private Lock first, second;             public A(Lock first, Lock second) {                         this.first = first;                         this.second = second;             }             public void run() {                         try {                                     first.lock();                                     System.out.println("Thread A got first lock.");                                     // do something                                     try {                                                 Thread.sleep( ((int)(3*Math.random()))*1000);...
Python programming: can someone please fix my code to get it to work correctly? The program...
Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks! # Program goals: # To simulate a car game. Focus is to build the engine for this game. # When we run the program, it...
In C programming: Using mutexes, semaphores, and spinlocks, you can sequence memory operations to prevent race...
In C programming: Using mutexes, semaphores, and spinlocks, you can sequence memory operations to prevent race conditions. It might make some sense to just chuck spinlocks out the window and use mutexes. Explain why mutexes would tend to relieve you of some of the problems inherent in spinlocks. Explain a situation in which those benefits might not be worth your time and you’d go with the spinlock anyway.
Java Programming: Can I get an example of a program that will allow 4 options? Example...
Java Programming: Can I get an example of a program that will allow 4 options? Example Output: Choose on of the options below: 1. Display all items in CSV file. (CSV file includes for example brand of phone, size, price) 2. Pick an item by linear searching 3. Pick an item by bineary searching 4. Quit Program
Write a program to create a tree randomly. You can use C++ programming language. The input...
Write a program to create a tree randomly. You can use C++ programming language. The input is the number of vertices in the tree, and the output is an adjacent list of the tree. (Managed to complete this assignment with a binary tree. But, was told I needed a general tree instead)
Programming Problem Design a program in java that can perform three different arithmetic operations based on...
Programming Problem Design a program in java that can perform three different arithmetic operations based on the user’s input. The three operations are 1. Summation of integers from 1 to m 2. Factorial of a given number n (n!) 3. Finding the leftmost digit of a given integer (note: you have to use int) This program should prompt the user a menu including four options, ask the user for one option, and perform the corresponding computation. This process will repeat...
How can I write a strong statement of purpose for a Master's in taxation program? My...
How can I write a strong statement of purpose for a Master's in taxation program? My undergraduate is in accounting. I do have leadership and internship experience.
Here is my C++ program so far. Is there anyway I can make it display an...
Here is my C++ program so far. Is there anyway I can make it display an error if the user enters a float? Thanks #include <iostream> using namespace std; // Creating a constant for the number of integers in the array const int size = 10; int main() { // Assigning literals to the varibles int a[size]; int sum=0; float avg; // For loop that will reiterate until all 10 integers are entered by the user for(int i=0; i<size; i++)...
Can you please see what I have done wrong with my program code and explain, This...
Can you please see what I have done wrong with my program code and explain, This python program is a guess my number program. I can not figure out what I have done wrong. When you enter a letter into the program, its supposed to say "Numbers Only" as a response. I can not seem to figure it out.. instead of an error message. import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if...
Hello Everyone, Can anyone tell me why my program will not run? I am trying to...
Hello Everyone, Can anyone tell me why my program will not run? I am trying to work on abstract base classes... not sure what is going on. import math from abc import ABC from abc import abstractmethod #TODO: convert this to an ABC class Shape(ABC): def __init__(self): self.name = "" def display(self): print("{} - {:.2f}".format(self.name, self.get_area())) #TODO: Add an abstractmethod here called get_area @abstractmethod def get_area(self): if self.name == "Circle": get_area()= 3.14 * radius * radius else: get_area() = self.length...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT