Sei sulla pagina 1di 18

PROCESS

SYNCHRONIZATION
IN DINING
PHILOSOPHERS
PROBLEM
Team Members:
• Krishna Kumar -18BEC0468
• Swapnadeep Sarkar-18BEC0773
• Agnitra Paul -18BEC0915
• Ion Jestin Paul -18BME0039
• Rajesh S V -18BME0082

Report submitted for the Final Project Review


of Course Code: CSE2005 – Operating System

Slot: L19+L20

Submitted to:
Professor: Dr. Jagalingam Pushparaj
Abstract
Process synchronization plays an important role in maintaining the consistency of shared
data. Both the software and hardware solutions are present for handling critical section
problem. But hardware solutions for critical section problem are quite difficult to implement.
In this review, we will discuss two software-based solution to handle critical section problem
i.e. Semaphore and Mutex in Dining Philosophers Problem.

The basic difference between semaphore and mutex is that semaphore is a signalling
mechanism i.e. processes perform wait() and signal() operation to indicate whether they are
acquiring or releasing the resource, while Mutex is locking mechanism, the process has to
acquire the lock on mutex object if it wants to acquire the resource.
Introduction
Process Synchronization in Operating System
Process Synchronization is an approach to facilitate process that utilization the common
information. It means sharing framework assets by processes so that simultaneous access to
shared information is dealt with, consequently, limiting the opportunity of data clashing.
Basedonsynchronization, processes areclassified as oneof theaccompanying two sorts:
• Independent Process: Execution of one process does not influences the execution
of different processes.
• Cooperative Process: Execution of one process influences the execution of
different processes.
Process synchronization issue emerges on account of Cooperative process additionally in light of
the fact that assets are partaken in Cooperative processes.
Race Condition
A few processes access and process the controls over similar information simultaneously, at that
point the result depends upon the specific order in which the access takes place.
Critical Section Problem
Critical section is acode section that can be accessed by just one process at once. Critical section
contains shared variables which should be synchronized to keep up consistency of information
variables.

Intheentrysegment,theprocessdemandsforpassageintheCriticalSection. Any
answer for the critical section issue must fulfil three necessities:
▪ Mutual Exclusion: If a process is executing in its critical section, at that point no
different process is permitted to execute in the critical section.
▪ Progress:If no process is executing inthecritical sectionand different processes
are waiting outside the critical section, at that point just those processes that are
not executing in their remainder segment can take part in choosing which will
enter in the critical section next, and the determination can't be delayed
indefinitely.
▪ Bounded Waiting: A bound must exist on the occasions that different processes
are permitted to enter their critical section after a process has made a request to
enter its critical section and before that request is allowed.

Peterson's Solution
Peterson's Solution is a traditional programming-based answer for the critical
section issue.
In Peterson's answer, we have two common factors:
• Booleanflag[i]:Initialized to FALSE, atfirst nobodyiskeenonentering
critical section
• int turn: The process whose turn is to enter the critical section.

Peterson’s Solution preserves all three conditions:


• Mutual Exclusion is assured as only one process can access the critical section at any
time.
• Progress is also assured, as a process outside the critical section does not
block other processes from entering the critical section.
• Bounded Waiting is preserved as every process gets a fair chance.
Disadvantages of Peterson’s Solution
• It involves Busy waiting
• It is limited to 2 processes.
Semaphore
Semaphore is a process synchronization tool. Semaphore is typically an integer
variable S that is initialized to the number of resources present in the system and the value
of semaphore can be modified only by two functions wait() and signal() apart from
initialization.

The wait() and signal() operation modify the value of the semaphore indivisibly. It means
that when a process is modifying the value of the semaphore, no other process can
simultaneously modify the value of the semaphore. Semaphore are distinguished by the
operating system in two categories Counting semaphores and Binary semaphore.

In Counting Semaphore, the semaphore S value is initialized to the number of resources


present in the system. Whenever a process wants to access the resource it
performs wait() operation on the semaphore and decrements the value of semaphore by
one. When it releases the resource, it performs signal() operation on the semaphore
and increments the value of semaphore by one. When the semaphore count goes to 0, it
means all resources are occupied by the processes. If a process need to use a resource
when semaphore count is 0, it executes wait() and get blocked until the value of
semaphore becomes greater than 0.

In Binary semaphore, the value of semaphore ranges between 0 and 1. It is similar to


mutex lock, but mutex is a locking mechanism whereas, the semaphore is a signalling
mechanism. In binary semaphore, if a process wants to access the resource it
performs wait() operation on the semaphore and decrements the value of semaphore
from 1 to 0. When it releases the resource, it performs a signal() operation on the
semaphore and increments its value to 1. If the value of semaphore is 0 and a process
want to access the resource it performs wait() operation and block itself till the current
process utilizing the resources releases the resource.
Mutex
Mutual Exclusion Object is shortly termed as Mutex. From the term mutual exclusion, we
can understand that only one process at a time can access the given resource. The mutex
object allows the multiple program threads to use the same resource but one at a time
not simultaneously.

When a program starts it request the system to creates a mutex object for a given
resource. The system creates the mutex object with a unique name or ID. Whenever the
program thread wants to use the resource it occupies lock on mutex object, utilizes the
resource and after use, it releases the lock on mutex object. Then the next process is
allowed to acquire the lock on mutex object.

Meanwhile, a process has acquired the lock on mutex object no other thread/process can
access that resource. If the mutex object is already locked, the process desiring to acquire
the lock on mutex object has to wait and is queued up by the system till the mutex object
is unlocked.
Description Semaphore Mutex

Basic Semaphore is a signalling Mutex is a locking


mechanism. mechanism.

Existence Semaphore is an integer Mutex is an object.


variable.

Function Semaphore allow multiple Mutex allow multiple


program threads to access a program thread to access a
finite instance of resources. single resource but not
simultaneously.

Ownership Semaphore value can be Mutex object lock is


changed by any process released only by the process
acquiring or releasing the that has acquired the lock
resource. on it.

Categorize Semaphore can be Mutex is not categorized


categorized into counting further.
semaphore and binary
semaphore.

Operation Semaphore value is Mutex object is locked or


modified using wait() and unlocked by the process
signal() operation. requesting or releasing the
resource.

Resources Occupied If all resources are being If a mutex object is already


used, the process locked, the process
requesting for resource requesting for resources
performs wait() operation waits and queued by the
and block itself till system till lock is released.
semaphore count become
greater than one.
Dining Philosophers Problem
Consider 5 philosophers are sitting on a dining with chairs, who want to eat a tasty dish
kept in the center of the table. Five plates are arranged in front of each chair. But there are
only 5 chopsticks. Each person wants to eat with two chopsticks so everyone can’t eat
simultaneously. So, each person has to wait for his left and right closest chopstick to get
free. So, each person eats for some time and sits idle and start thinking. Others wait for
the chopsticks to become free that is already in his left and right neighbor’s hands. If a
philosopher does not release chopstick and keeps eating continuously for long time then
deadlock like situation occurs. If he does not release chopstick until his dish finished others
have to wait for infinite time and other can get starved. Dining philosopher problem is like
classical synchronization problem that is equal to concurrency control problem.
Some simple solutions for such problems can be:
• By allowing four persons to sit on dining.
• Philosophers should be allowed to pick two chopsticks if both of his sides are
free.
• Use even or odd formula, means at a time either all even philosophers should
be allowed to pick chopsticks or odd one.
C Code Mutex Only
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<time.h>
#include<unistd.h>

void *func(int n);


pthread_t philosopher[5];
pthread_mutex_t chopstick[5];

int main()
{
int i,k;
void *msg;
double time_spent = 0.0;
clock_t begin = clock();
for(i=1;i<=5;i++)
{
k=pthread_mutex_init(&chopstick[i],NULL);
if(k==-1)
{
printf("\n Mutex initialization failed");
exit(1);
}
}
for(i=1;i<=5;i++)
{
k=pthread_create(&philosopher[i],NULL,(void
*)func,(int *)i);
if(k!=0)
{
printf("\n Thread creation error \n");
exit(1);
}
}
for(i=1;i<=5;i++)
{
k=pthread_join(philosopher[i],&msg);
if(k!=0)
{
printf("\n Thread join failed \n");
exit(1);
}
}
for(i=1;i<=5;i++)
{
k=pthread_mutex_destroy(&chopstick[i]);
if(k!=0)
{
printf("\n Mutex Destroyed \n");
exit(1);
}
}

clock_t end = clock();


time_spent += (double)(end - begin) /
CLOCKS_PER_SEC;
printf("\nTime elpased is %f seconds", time_spent);
return 0;
}

void *func(int n)
{
printf("\nPhilosopher %d is Thinking.",n);
pthread_mutex_lock(&chopstick[n]);
pthread_mutex_lock(&chopstick[(n+1)%5]);
printf("\nPhilosopher %d is Eating.",n);
sleep(3);
pthread_mutex_unlock(&chopstick[n]);
pthread_mutex_unlock(&chopstick[(n+1)%5]);
printf("\nPhilosopher %d Finished Eating.",n);
}
Output
C Code Semaphore Only
#include<stdio.h>
#include<fcntl.h>
#include<semaphore.h>
#include<sys/wait.h>
#include<pthread.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>

sem_t *sem[20];
int n;

int reader(int val)


{
printf("Philosopher %d is Thinking.\n",val+1);
while(1)
{
sem_wait(sem[val%n]);
if(!sem_trywait(sem[(val+1)%n]))
break;
else
sem_post(sem[val%n]);
}
printf("Philosopher %d is Eating.\n",val+1);
sleep(2);
sem_post(sem[val%n]);
sem_post(sem[(val+1)%n]);
printf("Philosopher %d Finished Eating.\n",val+1);
return 0;
}
int main()
{
pid_t cpid[5];
char semname[5];
int i,j=0;
double time_spent = 0.0;
clock_t begin = clock();
n = 5;
for(i=0;i<n;i++)
{
sprintf(semname,"%d",getpid()+i);

sem[i]=sem_open(semname,O_CREAT|O_EXCL,0666,1);
if(sem[i]==SEM_FAILED)
perror("Unable to create semaphore");

}
for(i=0;i<n;i++)
{
cpid[i]=fork();
if(cpid[i]==0)
break;
}
if(i==n)
{
int status;
for(i=0;i<n;i++)
waitpid(cpid[i],&status,WUNTRACED);
for(i=0;i<n;i++)
{
sem_close(sem[i]);
sprintf(semname,"%d",getpid()+i);
sem_unlink(semname);
}
}
else
reader(i);
sleep(3);
clock_t end = clock();
time_spent += (double)(end - begin) /
CLOCKS_PER_SEC;
printf("\nTime elpased is %f seconds", time_spent);
return 0;
}
Output
Observation: Comparing Time Taken by
Semaphore vs Mutex

Trial No. Semaphore Mutex


1 0.000926s 0.001009s
2 0.000965s 0.001179s
3 0.000960s 0.001651s
4 0.000803s 0.001596s
5 0.000968s 0.001485s
6 0.000976s 0.001319s
7 0.000998s 0.001217s
8 0.000943s 0.001079s
9 0.000919s 0.001321s
10 0.001047s 0.001451s
0.0018 Time Comparision
0.0016

0.0014

0.0012

0.001

0.0008

0.0006

0.0004

0.0002

0
Trial 1 Trial 2 Trial 3 Trail 4 Trail 5 Trail 6 Trail 7 Trail 8 Trail 9 Trail 10

Semaphore Mutex

Conclusion
Hence from the above study it can be observed that the Dining Philosophers Problem
executes faster using Semaphores than compared to using Mutex.
Thus, it can be concluded that Semaphore is a better option in case there are multiple
instances of resources available and in the case of single shared resource Mutex is a better
choice.
References
1. https://techliebe.com/synchronization-in-various-operating-systems/
2. https://tutorialwing.com/process-synchronization-in-operating-system/
3. https://www.geeksforgeeks.org/process-synchronization-set-1/
4. www.csee.wvu.edu/~jdmooney/classes/CS550/notes/tech/mutex/Peterson.html
5. http://iit.qau.edu.pk/books/OS_8th_Edition.pdf
6. http://web.stanford.edu/class/cs140/cgi-bin/lecture.php?topic=locks
7. https://cseweb.ucsd.edu/classes/fa05/CSE120/lectures/120-l5.Pdf
8. https://en.wikipedia.org/wiki/Semaphore_(programming)
PLAGIARISM SCAN REPORT

Date October 14, 2019 Words 1208

Exclude URL:

95% 5%
Unique Plagiarized

Content Checked for Plagiarism:


Report Generated on October 14, 2019 by prepostseo.com

Potrebbero piacerti anche