0% found this document useful (0 votes)
6 views96 pages

Thread Synchronization and Deadlock Management

Uploaded by

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

Thread Synchronization and Deadlock Management

Uploaded by

tmactopics
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-III

Thread, Process Synchronization, and Deadlock


PROCESS SYNCHRONIZATION
• Synchronization: The Critical section problem,
• Peterson’s solution,
• Synchronization hardware,
• Semaphores,
• Classical problems of synchronization, Monitors.
• Deadlocks: System model,
• Deadlock Characterization Methods for Handling Deadlocks,
• Deadlock Prevention,
• Deadlock avoidance,
• Deadlock Detection,
• Recovery from Deadlock.
Thread
• Thread is a smallest units of work of a process or Thread is a part of
process.
• Thread execution is done by thread schedular
• A process can have multiple threads
• One thread can communicates with another thread using Thread-Inter
Communication (TIC) approach
• Multiple Thread shares same resources of a process (i.e. code and data)
• Multiple Thread can run at a time and this techniques is known as
Multithreading. (Example: WordPad- spelling check is one thread, writing
in WordPad document is another thread. Similarly, VLC player also runs
multithread like progress bar of music, timer, video, and audio (These
thread runs simultaneously).
Thread Life Cycle
Process Vs Thread
Process Thread

System Call involves in process No system call is required

OS treats different process differently All user level threads treated as single
task for OS
Different process have different copy of Threads shares same copy of data and
data, files, and code code

Context switching is slower Context switching is faster

Blocking of one process will not block Blocking of one thread will block entire
another process thread

Independent Interdependent

Inter-process Communication is No IPC is required


required
Thread Working
• These are the working behavior of thread
• Single Thread Single-Task execution
• Multi-Thread Single Task Execution
• Single Thread Multi-Task Execution (Not Possible)
• Multi-Thread Multi-Task Execution
Thread Implementation
• Thread Implementation
• Thread class
• Runnable Interface

public void run()


{
// write thread working
}
Implementation Using Thread Class
import [Link].*; Thread class Methods
class Thread1 extends Thread
{ public void run()
public void run() public void start()
{
[Link](“Thread-1”);
public static sleep(int millisecond)
} public void join()
public static void main(String args[]) public void interrupt()
{
Thread1 t1=new Thread1();
[Link]();
}
}
Implementation Using Runnable Interface
import [Link].*;
Runnable Interface Methods
class Thread1 implements Runnable
{ public void run()
public void run()
{
[Link](“Thread-1”);
}
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread th=new Thread(t1);
[Link]();
}
}
Thread Execution
Implementation of Thread Working

• Single Thread Single-Task execution


• Multi-Thread Single Task Execution
• Single Thread Multi-Task Execution (Not Possible)
• Multi-Thread Multi-Task Execution
Single Thread Single Task
import [Link].*;
import [Link].*;
class Thread1 implements Runnable
class Thread1 extends Thread
{
{
public void run()
public void run()
{ {
[Link](“Thread-1”); [Link](“Thread-1”);
} }
public static void main(String args[]) public static void main(String args[])
{ {
Thread1 t1=new Thread1(); Thread1 t1=new Thread1();
[Link](); Thread th=new Thread(t1);
} [Link]();
} }
}
Multi Thread Single Task
import [Link].*; import [Link].*;
class Thread1 extends Thread class Thread1 implements Runnable
{ {
public void run()
public void run()
{
{
[Link](“Thread-1”);
[Link](“Thread-1”); }
} public static void main(String args[])
public static void main(String args[]) {
{ Thread1 t1=new Thread1();
Thread1 t1=new Thread1(); Thread th1=new Thread(t1);
[Link](); [Link]();
Thread1 t2=new Thread1(); Thread1 t2=new Thread1();
Thread th2=new Thread(t2);
[Link]();
[Link]();
}
}
} }
import [Link].*;
class Thread1 extends Thread
Multi Thread Multi Task
{
public void run()
{ [Link](“Thread-1”);
Class MultiThread
{
}
public static void main(String args[])
} {
class Thread2 extends Thread Thread1 t1=new Thread1();
{ [Link]();
Thread2 t2=new Thread2();
public void run()
[Link]();
{ [Link](“Thread-2”);
Thread3 t3=new Thread3();
} [Link]();
} }
class Thread3 extends Thread }
{
public void run()
{ [Link](“Thread-3”);
}
}
import [Link].*;
class Thread1 implements Runnable
Multi Thread Multi Task
{
public void run()
{ [Link](“Thread-1”);
Class MultiThread
{
}
public static void main(String args[])
} {
class Thread2 implements Runnable Thread1 t1=new Thread1();
{ Thread th1=new Thread(t1);
[Link]();
public void run()
Thread2 t2=new Thread2();
{ [Link](“Thread-2”);
Thread th2=new Thread(t2);
} [Link]();
} Thread3 t3=new Thread3();
class Thread3 implements Runnable Thread th3=new Thread(t3);
[Link]();
{
}
public void run() }
{ [Link](“Thread-3”);
}
}
Types of thread in OS
• User Level Thread
• User Level thread is created by Programmer
• Kernel Level Thread
• System (kernel) Level thread is created by Operating System
Difference between User level thread and
Kernel level thread
USER LEVEL KERNEL LEVEL

User level threads are managed by user level Kernel level threads are managed by OS (Using
library ( Using Procedure call) System call)

User level threads are faster in executions Kernel level threads are slower due to system
configuration and its execution parameters

Context switching is faster Context switching is slower

If one user level threads performs blocking, then If one system level threads performs blocking,
entire process gets blocked then process does not get blocked
Process Contention Scope (PCS):- User

Thread scheduling Thread


The contention takes place among threads
within a same process. The thread library
schedules the high-prioritized PCS thread to
access the resources via available LWPs
(priority as specified by the application
developer during thread creation).
System Contention Scope (SCS):- Kernel
Thread
The contention takes place among all threads
in the system. In this case, every SCS thread
is associated to each LWP by the thread
library and are scheduled by the system
scheduler to access the kernel resources.
Light Weight Process (LWP):-
Light-weight process are threads in the user
1-1 Scheduling : ( One kernel thread can provide service to space that acts as an interface for the user
one user thread) library thread (ULT) to access the physical
N:1 Scheduling : ( One kernel thread can provides services to CPU resources.
many user thread)
Thread Issue
• Thread issues in an operating system (OS) can include race
conditions, deadlocks, and synchronization problems. These
issues can occur when multiple threads access shared resources
or perform operations that depend on the order of execution.

• Types of thread issues


• The fork() and exec() system calls
• Thread Cancellation
• Signal handling
• Thread local storage
• Schedular activation
The fork() and exec() system calls
Process P1
• The fork() system call is used to create
duplicate process T1 T2 T3 T4
• If one thread calls fork() system call then
all thread will be duplicated of or new
process single threaded? 1. If only fork() is called, then new process
• Some UNIX system has chosen two will be created with multiple thread copy
version of fork()
• One that duplicates all threads T1- fork()
• Another that duplicates only the thread that
invoke the fork() system call 2. If exec() is called after fork then new process
• A call of exec() function from a process will be created with single copy of thread
with more than one thread will terminate
all running threads, and new image will T1- fork()
be loaded for execution. exec()

Here UNIX need to maintain two version of thread every time


Thread Cancellation
• Thread cancellation involves terminating a thread before it has completed
• For example, If multiple thread are concurrently searching through a
database , and one thread returns the result, the remaining thread might be
cancelled
• Another situation, when user presses a button on browser that stops a
webpage from loading any further
• A web page load using several threads- each image is loaded in the separate
thread
• When a user presses a stop button on the browser, all threads loading the
page are cancelled
• Types of thread cancellation
• Asynchronous : threads stop working immediately
• Deferred: It will be terminated after some time or successful completion of execution

A canceled thread may leave inconsistent user data in the system.


Signal Handling
• Signal is a special notification which is sent by one process to
another process or kernel may send signal to one process.
• Example, if kernel want to kill the process, then it will call
SIGKILL() method to kill the process abnormally. Similarly,
SIGTERM() method can be called to terminate the process
normally. If any interrupt is required, then process can send
message to kernel and vise-versa.
• All signal follows the same pattern of execution
• A signal is generated for the occurrence of an event
• The signal is delivered to the process to complete the event
• Once delivered the signal must be handled by a process
The problem with the signal is that it causes the thread to be in two simultaneous states, both
perpetually in a cancellation point, and executing instructions.
Thread local storage (Thread Pool)
• Thread pool consists of many thread with defined set of working ability.
If any request is coming from the user thread, then it will be checked,
and appropriate thread will be assigned to the user process for
execution.
• Here multi threading programming concepts is used
• Example,
T1
T1
Request T2
Request Web Server
• Web Server T2 T3
T3 T4

Thread Pool
• Each transactions must execute in a separate threat
• Each transaction might be assigned with unique thread
• Synchronization between thread is important here
Thread Specific data
In the following figure, thread T2 has a thread-specific data value of 12 associated with the key K3.
Thread T4 has the value of 2 associated with the same key.

Thread specific data allows each thread to possess a separate copy of data for the purpose of ensuring
isolated data and independent thread.
One challenge with thread-specific data is that when using
dynamically allocated thread, the programmer must ensure the key
allocation at run time with different data and threads
Schedular Activation
• The final issue is considered with multithreaded concept with
concern of kernel thread and user thread
• Here number of kernel thread must adjust dynamically to ensure
the best performance of user thread
• Thread scheduler works with one-to-one, many-to-one and many-
to-many services
• This data structure typically known as light-weight process (LWP)
Thread (Completed)
Process
• Process
• A program in execution is known as process
• Types of Process
• Co-operative Process
• When two process shares same Process
resource for its execution
• Independent Process
Co-operative Independent
• When process does not shares any
Process Process
resource for its execution
Process Execution Challenges
(Co-operative Process)
int shared= 5
Process (p1) Process (p2)
Here Both Processes
int x=shared; int y=shared; are Running Simultaneously
x++; y--;
sleep(1); sleep(1);
shared=x; shared=y;
Terminated Terminated

This Situation is known as Race Condition


Process Execution challenges
int a= 10
Process (p1) Process (p2) If output depends
on order of
read(a) read(a) execution
sleep(1) a++ Then it is known
a++; write(a); as Race Condition

write(a) Terminated
Terminated
Process Synchronization
PROCESS
When more than one process executes in our system
Then there two modes of operations are performed namely

(a) Serial mode (b) Parallel mode Co-operative Independent


Process Process

(a) Serial mode: Process executes one after another


Variable
(b) Parallel mode: Multiple process executes simultaneously
Memory

Code

Resources
Process Synchronization (Needs)
• Critical Section Problem and Mutual Exclusion
int shared= 5 A Program consists of Private section and
Shared resources.

Critical Section is a that part of code which a


int x=shared; int y=shared; process access sharable resource.

x++; y--;
Program
sleep(1); sleep(1); Private Section
Private Code (Independent
shared=x; shared=y; code Process)
Terminated Terminated
Critical Section
Shared
Code (Co-operative
Code
Process)
Critical Section Problem (Solution Approach)
• These are the three criteria must be satisfied for solving critical
section problem
• Mutual exclusion (Mandatory condition) (Process should access critical
section one after another)
• Progress (Mandatory condition) (only those process should be entered in
critical section who wants to use resources of critical section else not)
• Bounded wait (Optional condition) (There must be a maximum bound a
process can wait to get access of critical section)

Note: If two mandatory condition is satisfied then


system will not come in inconsistent state.
Turn variable

P0 P0 P1
{ while(1) while(1)
entry section { {
CS while(turn!=0); while(turn!=1);
exit section Critical Section Critical Section
Remainder Section turn=1 turn=0
} Remainder Section Remainder Section
} }
Flag Boolean variable
P0 P1 0 1
F F
while(1) while(1)
Flag
{ {
flag[0]=T flag[1]=T
while(flag[1]); while(flag[0]);
Critical Section Critical Section
flag[0]=F flag[1]=F
Remainder Section Remainder Section
} }
Peterson’s Solution
P0 P1
while(1) while(1)
{ {
flag[0]=T flag[1]=T
turn=1 turn=0
while( turn==1 && flag[1]==T); while(turn==0 && flag[0]==T);
Critical Section Critical Section Turn= 0/1

flag[0]=F flag[1]=F
Remainder Section Remainder Section
} }
Dekker’s Solution
Semaphores
A semaphores is an integer variable that apart from initialization, is accessed only through two
standard atomic operation i.e.; wait and signal.
Here S is semaphore variable
wait(s) signal(s) int s=1 Semaphore value must start with 1

{ { Use of Semaphores
• Critical Section Problem
while(s<=0); s=s+1; • Order of execution of Process
• Resource management
s=s-1; }
}
signal(s)
Semaphores (Critical Section Solution) {
s=s+1;
}
do do
{ {
entry section wait(s);
CS CS wait(s)
exit section signal(s); {
Remainder Section Remainder Section while(s<=0);
}while(T); }while(T); s=s-1;
}

P1 P2 P3 No. of Process
Semaphore
(Order of Process execution Solution)
P1 P2 P3
signal(s)
Order of execution {
s=s+1;
s1=0 s2=0 P2 P1 P3
}

wait(s1) P2 wait(s2) wait(s)


P1 signal(s1) P3 {
signal(s2) while(s<=0);
s=s-1;
}
Semaphores (Managing Resource Solution)
do S=5 signal(s) If number of replica of
{ one resources are
{
wait(s); multiple
P1 P2 P3 P4 P5 s=s+1;
CS Then more than one
Number of Process } process can come into
signal(s); critical section
wait(s)
Remainder Section
{
}while(T);
while(s<=0); For example Resource
= 5 Printers
This solution is used for parallel s=s-1;
processor execution } PR1 PR2 PR3 PR4 PR5
Number of Printers
Inter-process communication
• It is an approach to share data and information PROCESS
between two processes.
• Inter-process communication can be achieved
using two ways
• Shared memory Co-operative Independent
• Message Passing
Process Process
• In a shared memory model, a region of memory
that is shared by cooperating processes is
established Variable
• Processes can then exchange information by
reading and writing data to the shared region Memory
• In the message passing model, communication Code
takes place by means of messages exchanged
between the cooperating processes.
Resources
Classical problem on synchronization
• Producer consumer problem / Bounded Buffer problem
• Reader writer problem
• Dining Philosopher problem
• The sleeping barber problem
Producer Consumer (shared Memory)
signal(s)
void producer() void consumer()
{ {
{
Semaphore S=1 while(T) while(T) s=s+1;
{ {
Semaphore E=N
produce() //produce item wait(F) // underflow
}
Semaphore F=0 wait(E) // overflow wait(S)
wait(S) take() // buffer (pick item) wait(s)
N is the size of Buffer append() // buffer (add signal(S)
item )
signal(E)
{
signal(S)
signal(F)
use() // use produced
item
while(s<=0);
Buffer (Critical Section)
} } s=s-1;
} }
}
Reader Writer Problem (shared Memory)
Reader code
-----------------------------------
Writer code wait(mutex)
Semaphore mutex=1 readcount++
Semaphore wrt=1
---------------------
if(readcount==1)
readcount=0 wait(wrt)
wait(wrt)
Write operation signal(mutex)
signal(wrt) Read operation
Reader Writer
wait(mutex)
readcount - -
if(readcount==0)
CS signal(wrt)
signal(mutex)
Buffer (Critical Section)
Dining Philosopher problem

while(T) 1 1 1 1 1
{
chopstick
wait( chopstick [i]);
wait( chopstick [ (i+1) %5 ] );
eat();
signal( chopstick [i]);
signal( chopstick [ (i+1) %5 ] );
think();
}
Dining Philosopher Problem

Indian Chopstick
Dining Problem Solution
• Allow four philosopher at a time on dining table
• Allow six chopstick on the table
• Allow philosopher to pick the chopstick when both the chopsticks
are available
• All philosopher pick the right chopstick except last one ( last one
has to pick the left chopstick, if available then he has to pick left
right chopstick). – standard solution
Dining Philosopher problem (second solution)
The sleeping barber problem

Home Work
Problem statement
How to synchronize such that
one customer can come for
cutting
Working of Shared memory and Message
Passing

Shared Memory Message Passing


Example of IPC System
• Producer-Consumer problem (shared Memory)
• Client - server (Message Passing)
Client Server (Message Passing)
• Message passing means how a
message can be sent from one end
to the other end. Either it may be a
client-server model or it may be
from one node to another node.
• The formal model for message
passing has two timing models one
is synchronous and the other is
asynchronous.
• In message-passing systems,
processes communicate with one Stub - A stub is a representation (proxy) of the remote
another by sending and receiving object at client. It resides in the client. system; it acts
messages over a communication as a gateway for the client program.
channel such as a message queue, a
pipe, a socket. Skeleton − This is the object which resides on the
server side. stub communicates with skeleton for
message passing.
Hardware Synchronization (Test and set)
This synchronization is used in CISC (complex instruction set computer)
Synchronization (Completed)
Deadlock
• In a multiprogramming environment, several
processes may compete for a finite number of P1 P2
resources
• A process request for resources, if resources not Waiting Waiting
available at that time, the process enters at wating Assigned Assigned
state.
• Sometimes a waiting process is never again able R1 R2
to change state, because the resources it has
requested are held by other waiting process. This
situation is called as deadlock.
• A set of process is in a deadlock state when every
process in the set is waiting for an event that can
be caused only by the another process in the set.
Deadlock
Deadlock
Pay Tax

Give Service
Necessary condition of deadlock
• A deadlock can occur if all these four conditions occur in the
system simultaneously

• Mutual exclusion
• Hold and wait
• No pre-emption
• Circular wait
Mutual exclusion
• At least one resources must be held in a
non-sharable mode that is only one
process at a time can use the resource
• If another process request that
resource, the requesting process must
be delayed until the resource has been
released. And resource must be desired
by more than one process.
Hold and wait Hold

• A process must be holding at


least one resource and
waiting to acquire additional
resources that are currently
being held by other Wait

processes.

Example plate and spoon Wait R1

P1

Hold R2
No Pre-emption
• Resources can not be pre-empted
that is a resource can be released
only voluntarily by the process
holding it, after that process has
completed its task.
P1 P2

R1 R2

Two process competing for resource


Circular wait
• A set P0, P1, ---- Pn of waiting
processes must exist such that
P0 is waiting for resource held by
P1, P1 waiting for resource held
by P2 and Pn-1 waiting for
resource held by Pn, and Pn
waiting for resource held by P0.
Deadlock handling methods
1. Prevention: Design such protocols that there is no possibility of
deadlock
2. Avoidance: Try to avoid deadlock at runtime so ensuring that
system never enter in deadlocks state
3. Detection: we can allow the system to enter a deadlock state,
then detect it and recover
4. Ignorance: We can ignore the problem altogether and pretend
that deadlock never occur in the system
Deadlock prevention
• It means designing such systems where
there is no possibility of existence of
deadlock. For that we have to remove one
of the four necessary condition of
deadlock

Polio mission (GoI)


Prevention (Mutual exclusion)
• In prevention approach, there is
no solution for mutual exclusion
as resource can’t be made
sharable as it may go into
inconsistent state. It should work
in non-sharable mode.
Deadlock prevention (hold and wait)
• Conservative approach: Process is allowed
to run if and only if it has acquired all the
P2
resources P1

• Alternative protocol: A process may request


some resources and use them. Before it can
request any additional resources, it must
release all the resources that it is currently R1 R2
allocated
• Wait time out: We place a max time out, up
to which a process can wait. After which
process must release the resources and exit
Prevention (No pre-emption)
• If a process request some resources
• We first check whether they are available. If they are we allocate them
• If they are not

• We check whether they are allocated to some other process that is waiting
for some additional resources. If so, we pre-empt the desired resources from
the waiting process and allocate them to the requesting process
(Considering priority)

• If the resources are neither available nor held by a waiting process, the
requesting process must wait, or may allow to pre-empt resource of a
running process considering priority
Prevention (Circular wait)
• We can eliminate circular wait problem by giving a natural number
mapping to every resource and then any process can request only
in the increasing order and if a process wants a lower number,
then process must first release all the resources larger than that
number and give a fresh request.
Problem with prevention
• Different deadlock prevention
approach put different type of
restrictions or conditions on the
processes and resources
because of which system
becomes slow, does not make
proper resource utilization, and
reduces system throughput.
Deadlock Avoidance

Banker Algorithm
Banker Algorithm
• In order to, avoid deadlock in run
time, system try to maintain some
books like a banker, whenever
someone ask for loan (resource), it
is granted only when the books
allow.
Deadlock avoidance (Banker Algorithm)
• To avoiding deadlock, we require additional information about
how resources are to be requested, which resources a process
will request during its lifetime
• With this additional knowledge, the operating system can decide
for each request whether process should wait or not.
Banker Algorithm
Safe Sequence
• Some sequence in which we can
satisfies demand of every process
without going into deadlock, if yes,
this sequence is known as safe
sequence.
• Safe sate : If there exist at least one
safe sequence
• Unsafe state: If there exist no
possible safe sequence
Banker Algorithm (Find the safe sequence)

Q1 Find the safe state Q2 Find the safe state


Question (GATE-2014)
Process Allocated MAX Current Need (Requirement)
X Y Z X Y Z X Y Z
P0 0 0 3 8 4 3 8 4 0
P1 3 2 0 6 2 0 3 0 0
P2 2 1 1 3 3 3 1 2 2

Available ( X=3 , Y=2 , Z=0)

Which of the process can not be completed.

Does system occur in unsafe state


Questions (GATE-2014)
• An operating system uses the Banker’s algorithm for deadlock avoidance when managing the
allocation of three resource types X, Y, and Z to three processes P0, P1, and P2. The table given
below presents the current system state. Here, the Allocation matrix shows the current number of
resources of each type allocated to each process and the Max matrix shows the maximum number
of resources of each type required by each process during its execution.

There are 3 units of type X, 2 units of type Y and 2 units of type Z still available. The system is
currently in a safe state. Consider the following independent requests for additional resources in the
current state:
REQ1: P0 requests 0 units of X, 0 units of Y and 2 units of Z
REQ2: P1 requests 2 units of X, 0 units of Y and 0 units of Z
Safety Algorithm
Safety Algorithm

Find the safe state


Resource Allocation Graph (RAG)
Deadlock can also be described in
terms of a directed graph called a
system resource allocation graph.
This graph consists of set of
vertices V and set of Edge E

The set of vertices V is partitioned


into two different types of nodes
P= {P1, P2, P3, .. Pn} the set of
This graph is used to represent banker algorithm active process in the system, and
Pi -> Rj (Resource Request) R= {R1, R2, R3… Rn} set of
Rj-> Pi ( Resource Allocated) resources types in the system.
Resource Allocation Graph (RAG)
Resource Resource Resource Resource
(R1) (R2) (R1) (R2)
Process Allocation Request

P1 0 1 1 0

P2 1 0 0 0

P3 1 0 0 1

P4 0 1 0 0

Current Available Resource ( R1, R2) = (0, 0) Max Resource ( R1, R2) = (2, 2)
Question

Find whether system is in deadlock state Find whether system is in deadlock state
Find the safe sequence Find the safe sequence
Question

Find whether system is in deadlock state


Find whether system is in deadlock state Find the safe sequence
Find the safe sequence
Deadlock detection and recovery
• Once a deadlock is detected there is two options for recovery
from a deadlock
• Process termination
• Abort all deadlock processes
• Abort one process at a time until the deadlock is resolved
• Resource Pre-emption
• Selecting a victim resource
• Partial or complete rollback of resource
Deadlock Ignorance (Ostrich Algorithm)
• Operating system behaves like there is
no concept of deadlock
• Ignoring deadlock can lead to system
performance issues as resource get
locked by idle processes
• Despite this, many operating system opt
for this approach to save on the cost of
implementing deadlock detection
• Deadlock are often rare, so the trade-off
may seem justified. Manual restarts may
be required when a deadlock occurs.
Process Synchronization
• Lock
• Spin lock
• Mutex
• Semaphore
• Monitor
Lock in operating System
Entry section
while(lock != 0);
Lock = 1;
critical section
Lock = 0;
Remainder Section
Spinlock
• Spinlock is a synchronization mechanism
used in operating systems to protect
shared resources from single access by
multiple threads or processes. Unlike
other synchronization methods such
as semaphores or mutexes, spinlocks use a
busy-wait method, where a thread
continuously selects a lock until it
becomes available.
mutex m
Mutex in Operating system Lock (m)
CS
Unlock(m)

• A mutex is different from a binary semaphore, -----------------------------------------


which provides a locking mechanism. It stands do
for Mutual Exclusion Object. {
Lock()
• Mutex is mainly used to provide mutual exclusion Critical Section
to a specific portion of the code so that the process Unlock ()
can execute and work with a particular section of Remainder Section
}while(true);
the code at a particular time.
• A mutex enforces strict ownership. Only the thread -----------------------------------------
that locks the mutex can unlock it. mutex m
wait (m)
• It is specifically used for locking a resource to CS
ensure that only one thread accesses it at a time. signal(m)
Advantage and Disadvantage of Mutex
• Advantages of Mutex
• No race condition arises, as only one process is in the critical
section at a time.
• Data remains consistent and it helps in maintaining integrity.
• It is a simple locking mechanism that into a critical section and is
released while leaving the critical section.
• Disadvantages of Mutex
• If after entering into the critical section, the thread sleeps or gets
preempted by a high-priority process, no other thread can enter into
the critical section. This can lead to starvation.
Semaphores
A semaphores is an integer variable that apart from initialization, is accessed only through two
standard atomic operation i.e.; wait and signal.
Here S is semaphore variable
wait(s) signal(s) int s=1 Semaphore value must start with 1

{ { Use of Semaphores
• Critical Section Problem
while(s<=0); s=s+1; • Order of execution of Process
• Resource management
s=s-1; }
}
Semaphore
(Violating rules of Mutual Exclusion)
signal(s)
{
s=s+1;
s=1 P2 P1 P3
}

wait(s) P2 P3 wait(s)
P1 signal(s) signal(s) {
signal(s) while(s<=0);
s=s-1;
}
Difference between Mutex and Semaphore
Mutex Semaphore
A mutex is an object A semaphore is an integer
Mutex works upon the locking mechanism Semaphore uses signaling mechanism
Operation Operation
Lock Wait
Unlock Signal
Mutex does not have any subtypes Semaphore is of two types
Counting Semaphore
Binary Semaphore
A mutex can only be modified by the process that is Semaphore works with two atomic operations
requesting or releasing a resource (wait and signal) which can modify it
If the mutex is locked then the process needs to wait in the If the process needs a resource, and no resource
process queue, and mutex can only be accessed once the is free. So, the process needs to perform a wait
lock is released operation until the semaphore value is greater
then zero.
Monitor
• Monitors are a higher-level synchronization
construct that simplifies process
synchronization by providing a high-level
abstraction for data access and
synchronization.
• Monitors are implemented as programming
language constructs, typically in object-
oriented languages, and provide mutual
exclusion, condition variables, and data
encapsulation in a single construct.
• The key advantage of using monitors for
process synchronization is that they provide a
simple, high-level abstraction that can be
used to implement complex concurrent
systems.
Monitor

One process can access


Shared resource at a time

Waiting Monitor Queue


Lock if one process already in
Shared area
UNIT – III (Completed )

You might also like