Date post: | 18-Oct-2015 |
Category: |
Documents |
Upload: | nurgazy-nazhimidinov |
View: | 17 times |
Download: | 0 times |
of 65
5/28/2018 CENG334 2013 W06 Synchronization Monitors
1/65
1
CENG334
Introduction to Operating Systems
Erol Sahin
Dept of Computer Eng.Middle East Technical University
Ankara, TURKEY
URL:http://kovan.ceng.metu.edu.tr/ceng334
Petersons AlgorithmMonitors, Condition variablessTopics:
Monitors
Condition Variables
5/28/2018 CENG334 2013 W06 Synchronization Monitors
2/65
2
Petersons Algorithm
int flag[2] = {0, 0};
int turn;
P0:do{
flag[0] = 1;
turn = 1;
while (flag[1] == 1 && turn == 1)
{ // busy wait
}
// critical section
flag[0] = 0;
//remainder section
}while(1);
P1:do{
flag[1] = 1;
turn = 0;
while (flag[0] == 1 && turn == 0)
{ // busy wait
}
// critical section
flag[1] = 0;
// remainder section
} while(1);
turn : indicates whose turn is it to enter critical section. If turn==iprocess Pi is allowed to get in.
flag[2]: indicates if process Pi is ready to enter critical section. Ifflag[i]is set, then Pi is ready to enter critical section.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
3/65
3
Petersons Algorithm
int flag[2] = {0, 0};
int turn;
P0:do{
flag[0] = 1;
turn = 1;
while (flag[1] == 1 && turn == 1)
{ // busy wait
}
// critical section
flag[0] = 0;
//remainder section
}while(1);
P1:do{
flag[1] = 1;
turn = 0;
while (flag[0] == 1 && turn == 0)
{ // busy wait
}
// critical section
flag[1] = 0;
// remainder section
} while(1);
Mutual Exclusion: Only one process Pi (the one which set turn=i last) enters the criticalsection.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
4/654
Petersons Algorithm
int flag[2] = {0, 0};
int turn;
P0:do{
flag[0] = 1;
turn = 1;
while (flag[1] == 1 && turn == 1)
{ // busy wait
}
// critical section
flag[0] = 0;
//remainder section
}while(1);
P1:do{
flag[1] = 1;
turn = 0;
while (flag[0] == 1 && turn == 0)
{ // busy wait
}
// critical section
flag[1] = 0;
// remainder section
} while(1);
Progress: If process P1 is not in critical section then flag[1] = 0. Therefore while loop of P0quits immediately and P0 can get into its critical section. And vice versa..
Bounded waiting: Process Pi keeps waiting in spinlocking only while the other process is inits critical section.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
5/655
Petersons Algorithm
int flag[2] = {0, 0};
int turn;
P0:do{
flag[0] = 1;
turn = 1;
while (flag[1] == 1 && turn == 1)
{ // busy wait
}
// critical section
flag[0] = 0;
//remainder section
}while(1);
P1:do{
flag[1] = 1;
turn = 0;
while (flag[0] == 1 && turn == 0)
{ // busy wait
}
// critical section
flag[1] = 0;
// remainder section
} while(1);
Uses spinlocking for waiting.No strict alternation is required between processes. That is, P0,P0,P0,P1,P1 is doable.Requires that processes alternate between critical and remainder sections.Can be extended to n processes, only if n is known apriori (in advance). HOW?
5/28/2018 CENG334 2013 W06 Synchronization Monitors
6/656
Petersons Algorithm
int flag[2] = {0, 0};
int turn;
P0:do{
flag[0] = 1;
turn = 1;
while (flag[1] == 1 && turn == 1)
{ // busy wait
}
// critical section
flag[0] = 0;
//remainder section
}while(1);
P1:do{
flag[1] = 1;
turn = 0;
while (flag[0] == 1 && turn == 0)
{ // busy wait
}
// critical section
flag[1] = 0;
// remainder section
} while(1);
Prone to priority inversion:Assume that P0 has a higher priority than P1.When P1 is in its critical section, P0 may get scheduled to do spinlocking.P1 never gets scheduled to finish its critical section and both processes end up waiting.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
7/657
Issues with Semaphores
Much of the power of semaphores derives from calls to
down() and up() that are unmatched
See previous example!
Unlike locks, acquire() and release() are not always paired.
This means it is a lot easier to get into trouble with semaphores.
More rope
Would be nice if we had some clean, well-defined language
supportfor synchronization...
Java does!
Adapted from Matt Welshs (Harvard University) slides.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
8/658
Monitors
A monitoris an object intended to be used safely
by more than one thread.
The defining characteristic of a monitor is that its
methods are executed with mutual exclusion.
That is, at each point in time, at most one thread may be
executing any of its methods.
also provide Condition Variables (CVs) for
threads to temporarily give up exclusive access,
in order to wait for some condition to be met,
before regaining exclusive access and resuming their task.
Use CVs for signaling other threads that such
conditionshave been met.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
9/659
Condition Variables
Conceptually a condition variable (CV) is a queue of threads,
associated with a monitor, upon which a thread may wait for
some assertion to become true.
Threads can use CVs
to temporarily give up exclusive access, in order to wait for
some condition to be met, before regaining exclusive access and resuming their task.
for signaling other threads that such conditionshave been met.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
10/6510
Monitors
This style of using locks and CV's to protect access to a sharedobject is often called a monitor
Think of a monitor as a lock protecting an object, plus a queue of waiting threads.
Shared data
Methods accessing
shared data
Waiting threads
At most one thread
in the monitor at atime
How is this different than a lock???
Adapted from Matt Welshs (Harvard University) slides.
M i
5/28/2018 CENG334 2013 W06 Synchronization Monitors
11/6511
Monitors
Shared data
Methods accessingshared data
unlocked
Adapted from Matt Welshs (Harvard University) slides.
M it
5/28/2018 CENG334 2013 W06 Synchronization Monitors
12/6512
Monitors
Shared data
Methods accessingshared data
locked
zzzz...
zzzz...
Sleeping thread no longer inthe monitor.(But not on the waiting queue either! Why?)
Adapted from Matt Welshs (Harvard University) slides.
M it
5/28/2018 CENG334 2013 W06 Synchronization Monitors
13/6513
Monitors
Shared data
Methods accessingshared data
lockedMonitor stays locked!(Lock now owned bydifferent thread...)
zzzz...
notify()
Adapted from Matt Welshs (Harvard University) slides.
M it
5/28/2018 CENG334 2013 W06 Synchronization Monitors
14/6514
Monitors
Shared data
Methods accessingshared data
locked
notify()
Adapted from Matt Welshs (Harvard University) slides.
Monitors
5/28/2018 CENG334 2013 W06 Synchronization Monitors
15/65
15
Monitors
Shared data
Methods accessingshared data
locked
No guarantee which order threads get into the monitor.(Not necessarily FIFO!)
Adapted from Matt Welshs (Harvard University) slides.
Bank Example
5/28/2018 CENG334 2013 W06 Synchronization Monitors
16/65
16
Bank Example
monitor Bank{
int TL = 1000;condition haveTL;
void withdraw(int amount) {if (amount > TL)
wait(haveTL);TL -= amount;
}
void deposit(int amount) {TL += amount;notify(haveTL);
}
}
Bank Example
5/28/2018 CENG334 2013 W06 Synchronization Monitors
17/65
17
Bank Example
monitor Bank{
int TL = 1000;condition haveTL;
void withdraw(int amount) {while(amount > TL)
wait(haveTL);TL -= amount;
}
void deposit(int amount) {TL += amount;notifyAll(haveTL);
}
}
Hoare vs Mesa Monitor Semantics
5/28/2018 CENG334 2013 W06 Synchronization Monitors
18/65
18
Hoare vs. Mesa Monitor SemanticsThe monitor notify() operation can have two different meanings:
Hoare monitors (1974) notify(CV) means to run the waiting thread immediately Causes notifying thread to block
Mesa monitors (Xerox PARC, 1980) notify(CV) puts waiting thread back onto the ready queuefor the monitor
But, notifying thread keeps running
Adapted from Matt Welshs (Harvard University) slides.
Hoare vs Mesa Monitor Semantics
5/28/2018 CENG334 2013 W06 Synchronization Monitors
19/65
19
Hoare vs. Mesa Monitor SemanticsThe monitor notify() operation can have two different meanings:
Hoare monitors (1974) notify(CV) means to run the waiting thread immediately Causes notifying thread to block
Mesa monitors (Xerox PARC, 1980) notify(CV) puts waiting thread back onto the ready queuefor the monitor
But, notifying thread keeps running
What's the practical difference? In Hoare-style semantics, the conditionthat triggered the notify()
will always be truewhen the awoken thread runs
For example, that the buffer is now no longer empty
In Mesa-style semantics, awoken thread has to recheck the con di t ion Since another thread might have beaten it to the punch
Adapted from Matt Welshs (Harvard University) slides.
Hoare Monitor Semantics
5/28/2018 CENG334 2013 W06 Synchronization Monitors
20/65
20
Hoare Monitor SemanticsHoare monitors (1974)
notify(CV) means to run the
waiting thread immediately
Causes notifying thread to block
The signaling thread must
wait outside the monitor (at
least) until the signaled
thread relinquishesoccupancy of the monitor
by either returning or by
again waiting on a
condition.
Mesa Monitor Semantics
http://upload.wikimedia.org/wikipedia/en/d/db/Monitor_(synchronization)-SU.png5/28/2018 CENG334 2013 W06 Synchronization Monitors
21/65
21
Mesa Monitor SemanticsMesa monitors (Xerox PARC,
1980)
notify(CV) puts waiting thread back
onto the ready queuefor themonitor
But, notifying thread keeps running
Signaling does not cause the
signaling thread to loseoccupancy of the monitor.
Instead the signaled threads
are moved to the e queue.
http://upload.wikimedia.org/wikipedia/en/1/15/Monitor_(synchronization)-Mesa.png5/28/2018 CENG334 2013 W06 Synchronization Monitors
22/65
22
Hoare vs. Mesa monitorsNeed to be careful about precise definition of signal and wait.
while (n==0) {wait(not_empty); // If nothing, sleep
}item = getItemFromArray(); // Get next item
Why didnt we do this?
if (n==0) {wait(not_empty); // If nothing, sleep
}removeItemFromArray(val); // Get next item
Answer: depends on the type of scheduling Hoare-style (most textbooks):
Signaler gives lock, CPU to waiter; waiter runs immediately
Waiter gives up lock, processor back to signaler when it exits critical section or if itwaits again
Mesa-style (Java, most real operating systems):
Signaler keeps lock and processor
Waiter placed on ready queue with no special priority
Practically, need to check condition again after wait
5/28/2018 CENG334 2013 W06 Synchronization Monitors
23/65
23
Revisit: Readers/Writers Problem
Correctness Constraints:
Readers can access database when no writers
Writers can access database when no readers or writers
Only one thread manipulates state variables at a time
State variables (Protected by a lock called lock):
int NReaders: Number of active readers; initially = 0
int WaitingReaders: Number of waiting readers; initially = 0
int NWriters: Number of active writers; initially = 0
int WaitingWriters: Number of waiting writers; initially = 0
Condition canRead = NIL
Conditioin canWrite = NIL
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
24/65
24
Readers and Writers
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);
--WaitingWriters;}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
Signal(CanRead);else
Signal(CanWrite);}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);
--WaitingReaders;}++NReaders;Signal(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
Signal(CanWrite);
}
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
25/65
25
Readers and Writers
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);
--WaitingWriters;}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
Signal(CanRead);else
Signal(CanWrite);}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);
--WaitingReaders;}++NReaders;Signal(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
Signal(CanWrite);
}
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
26/65
26
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);
--WaitingWriters;}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
notify(CanRead);else
notify(CanWrite);}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);
--WaitingReaders;}++NReaders;Signal(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
notify(CanWrite);
}
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
27/65
27
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);
--WaitingWriters;}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
notify(CanRead);else
notify(CanWrite);}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);--WaitingReaders;
}++NReaders;notify(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
notify(CanWrite);
}
Understanding the Solution
5/28/2018 CENG334 2013 W06 Synchronization Monitors
28/65
28
g
A writer can enter if there are no other active writers and no readersare waiting
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
29/65
29
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);
--WaitingWriters;}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
notify(CanRead);else
notify(CanWrite);}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);--WaitingReaders;
}++NReaders;notify(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
notify(CanWrite);
}
Understanding the Solution
5/28/2018 CENG334 2013 W06 Synchronization Monitors
30/65
30
g
A reader can enter if There are no writers active or waiting
So we can have many readers active all at once
Otherwise, a reader waits (maybe many do)
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
31/65
31
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);
--WaitingWriters;}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
notify(CanRead);
elsenotify(CanWrite);
}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);--WaitingReaders;
}++NReaders;notify(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
notify(CanWrite);
}
Understanding the Solution
5/28/2018 CENG334 2013 W06 Synchronization Monitors
32/65
32
When a writer finishes, it checks to see if any readers are waiting If so, it lets one of them enter
That one will let the next one enter, etc
Similarly, when a reader finishes, if it was the last reader, it lets awriter in (if any is there)
Readers and Writers
5/28/2018 CENG334 2013 W06 Synchronization Monitors
33/65
33
Monitor ReadersNWriters {int WaitingWriters, WaitingReaders,NReaders, NWriters;
Condition CanRead, CanWrite;
Void BeginWrite(){
if(NWriters == 1 || NReaders > 0){
++WaitingWriters;wait(CanWrite);--WaitingWriters;
}NWriters = 1;
}Void EndWrite(){
NWriters = 0;if(WaitingReaders)
notify(CanRead);
elsenotify(CanWrite);
}
Void BeginRead(){
if(NWriters == 1 || WaitingWriters > 0){
++WaitingReaders;Wait(CanRead);--WaitingReaders;
}++NReaders;notify(CanRead);
}
Void EndRead(){
if(--NReaders == 0)
notify(CanWrite);
}
Understanding the Solution
5/28/2018 CENG334 2013 W06 Synchronization Monitors
34/65
34
It wants to be fair If a writer is waiting, readers queue up
If a reader (or another writer) is active or waiting, writers queue up
this is mostly fair, although once it lets a reader in, it lets ALL waiting readers in allat once, even if some showed up afterother waiting writers
The Big Picture
5/28/2018 CENG334 2013 W06 Synchronization Monitors
35/65
35
The point here is that getting synchronization right is hard
How to pick between locks, semaphores, condvars, monitors???
Locksare very simple for many cases. Issues: Maybe not the most efficient solution
For example, can't allow multiple readers but one writer inside a standard lock.
Cond it ion var iablesallow threads to sleep while holding a lock Just be sure you understand whether they use Mesa or Hoare semantics!
Semaphoresprovide pretty general functionality But also make it really easy to botch things up.
Adapted from Matt Welshs (Harvard University) slides.
Barbershop problem
5/28/2018 CENG334 2013 W06 Synchronization Monitors
36/65
36
A barber shop consists of a waitingroom with N chairs, and the barberroom containing the barber chair.
If there are no customers to beserved, the barber goes to sleep.
If a customer enters the barber shopand all chairs are occupied, thenthe customer leaves the shop.
If the barber is busy, but chairs areavailable, then the customer sits inone of the free chairs.
If the barber is asleep, the customerwakes up the barber.
Monitor template
5/28/2018 CENG334 2013 W06 Synchronization Monitors
37/65
37
monitor BarberShop{condition waitingForCustomers,
waitingForBarbers;int waiting = 0; // number of waiting customers in chairsvoid barber(){
.cutHair();
.}void customer(){
.getHairCut(); // may not be executed if all chairs are full.
}}
void barberThread(){while(1)
BarberShop.barber();}void customerThread(){
BarberShop.customer();}
Semaphore template
5/28/2018 CENG334 2013 W06 Synchronization Monitors
38/65
38
semaphore customer = 0; // number of customers waiting for servicesemaphore barber = 0; // number of barbers waiting for customers
semaphore mutex = 1; // for mutual exclusionint waiting = 0; //customers who are sitting in chairs
void barberThread(){while (1) {
.cutHair();.
}}
void customerThread(){..getHairCut(); // may not be executed if all chairs are full.
}
Checking your code
5/28/2018 CENG334 2013 W06 Synchronization Monitors
39/65
39
B: Does the Barber sleep when there are no customers.
BC: Does the first customer wake up the sleeping barber and
have his haircut.
BCC: Does the second customer waits for the barber while he isgiving a haircut to the first customer.
BCCCCCCC: Does the 7thcustomer (first customer having ahaircut, the next 5 customers waiting), exits without getting ahaircut?
BCCCCC: Does the barber wake up a waiting customer afterfinishing the haircut of the first customer?
Finally, is the solution efficient? Sending more notify signals thanneeded, or using more variables is not good practise.
CENG334
5/28/2018 CENG334 2013 W06 Synchronization Monitors
40/65
40
CENG334
Introduction to Operating Systems
Erol Sahin
Dept of Computer Eng.
Middle East Technical UniversityAnkara, TURKEY
URL:http://kovan.ceng.metu.edu.tr/~erol/Courses/ceng334
DeadlocksTopics:
DeadlocksDining philosopher problem
Whats a deadlock?
5/28/2018 CENG334 2013 W06 Synchronization Monitors
41/65
41
Deadlock
5/28/2018 CENG334 2013 W06 Synchronization Monitors
42/65
42
A deadlock happens when Two (or more) threads waiting for each other
None of the deadlocked threads ever make progress
Mutex
1
Thread 1
Thread 2Mutex
2
holds
holds
waits for
waits for
Adapted from Matt Welshs (Harvard University) slides.
Deadlock DefinitionTwo kinds of resources:
5/28/2018 CENG334 2013 W06 Synchronization Monitors
43/65
43
Two kinds of resources: Preemptible: Can take away from a thread
e.g., the CPU
Non-preemptible: Can't take away from a thread
e.g., mutex, lock, virtual memory region, etc.
Why isn't it safe to forcibly take a lock away from a thread?
Starvation
A thread never makes progress because other threads are using a resource it needs
Deadlock A circular waiting for resources
Thread A waits for Thread B
Thread B waits for Thread A
Starvation Deadlock
Adapted from Matt Welshs (Harvard University) slides.
Dining PhilosophersClassic deadlock problem
5/28/2018 CENG334 2013 W06 Synchronization Monitors
44/65
44
Classic deadlock problem Multiple philosophers trying to lunch
One chopstick to left and right of each philosopher
Each one needs two chopsticks to eat
Adapted from Matt Welshs (Harvard University) slides.
Dining PhilosophersWhat happens if everyone grabs the chopstick to their right?
5/28/2018 CENG334 2013 W06 Synchronization Monitors
45/65
45
What happens if everyone grabs the chopstick to their right? Everyone gets one chopstick and waits forever for the one on the left
All of the philosophers starve!!!
Adapted from Matt Welshs (Harvard University) slides.
Deadlock Characterization
5/28/2018 CENG334 2013 W06 Synchronization Monitors
46/65
46
Mutual exclusion: only one process at a time can use a resource.
Hold and wait: a process holding at least one resource is waiting to acquire
additional resources held by other processes.
No preemption: a resource can be released only voluntarily by the process
holding it, after that process has completed its task.
Circular wait: there exists a set {P0, P1, , P0} of waiting processes such
that
P0 is waiting for a resource that is held by P1,
P1is waiting for a resource that is held by P2, ,
Pn1is waiting for a resource that is held by Pn, and
P0is waiting for a resource that is held by P0.
Deadlock can arise if four conditions hold simultaneously.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Deadlock Prevention
R t i th t b d t th t t l t f
5/28/2018 CENG334 2013 W06 Synchronization Monitors
47/65
47
Restrain the ways request can be made to ensure that at least one of
the four conditions DO NOT HOLD!
Mutual Exclusion not required for sharable resources;
must hold for non-sharable resources,
such as a printer.
Hold and Wait
must guarantee that whenever a process requests a resource, it does not hold any
other resources.
Require process to request and be allocated all its resources before it begins
execution, or allow process to request resources only when the process has none.
low resource utilization;
starvation possible.
Deadlock Prevention (Cont.)No Preemption
5/28/2018 CENG334 2013 W06 Synchronization Monitors
48/65
48
No Preemption
If a process that is holding some resources requests another resource that cannot
be immediately allocated to it, then all resources currently being held are released.
Preempted resources are added to the list of resources for which the process is
waiting.
Process will be restarted only when it can regain its old resources, as well as the
new ones that it is requesting.
Can be applied to resources whose state can be saved such as CPU, and memory.
Not applicable to resources such as printer and tape drives.
Circular Wait
impose a total ordering of all resource types, and
require that each process requests resources in an increasing order of
enumeration.
Circular Wait - 1
5/28/2018 CENG334 2013 W06 Synchronization Monitors
49/65
49
Each resource is given an ordering:
F(tape drive) = 1
F(disk drive) = 2
F(printer) = 3
F(mutex1) = 4
F(mutex2) = 5
.
Each process can request resources only in increasing order of
enumeration.
A process which decides to request an instance of Rj should first
release all of its resources that are F(Ri) >= F(Rj).
Circular Wait - 2
5/28/2018 CENG334 2013 W06 Synchronization Monitors
50/65
50
For instance an application program may use ordering among all of itssynchronization primitives:
F(semaphore1) = 1 F(semaphore2) = 2
F(semaphore3) = 3
.
After this, all requests to synchronization primitives should be made only
in the increasing order: Correct use:
down(semaphore1);
down(semaphore2);
Incorrect use:
down(semaphore3);
down(semaphore2);
Keep in mind that its the application programmers responsibility toobey this order.
Methods for Handling Deadlocks
H h ld h dl d dl k
5/28/2018 CENG334 2013 W06 Synchronization Monitors
51/65
51
How should we handle deadlocks
Ensure that the system will neverenter a
deadlock state.
Allow the system to enter a deadlock state and
then recover.
Ignore the problem and pretend that deadlocks
never occur in the system; used by most
operating systems, including UNIX.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Dining PhilosophersHow do we solve this problem??
5/28/2018 CENG334 2013 W06 Synchronization Monitors
52/65
52
(Apart from letting them eat with forks.)
Adapted from Matt Welshs (Harvard University) slides.
How to solve this problem?Solution 1: Don't wait for chopsticks
5/28/2018 CENG334 2013 W06 Synchronization Monitors
53/65
53
Grab the chopstick on your right
Try to grab chopstick on your left
If you can't grab it, put the other one back down
Breaks no preemptionconditionno waiting!
Solution 2: Grab both chopsticks at once Requires some kind of extra synchronization to make it atomic
Breaks multiple independent requestscondition!
Solution 3: Grab chopsticks in a globally defined order Number chopsticks 0, 1, 2, 3, 4
Grab lower-numbered chopstick first
Means one person grabs left hand rather than right hand first!
Breaks circular dependencycondition
Solution 4: Detect the deadlock condition and break out of it Scan the waiting graph and look for cycles
Shoot one of the threads to break the cycle
Adapted from Matt Welshs (Harvard University) slides.
Deadlock AvoidanceRequires that the system has some
5/28/2018 CENG334 2013 W06 Synchronization Monitors
54/65
54
additional a priori information available.
Simplest and most useful model requires that each
process declare the maximum number of resources
of each type that it may need.
Is this possible at all?
The deadlock-avoidance algorithm dynamically
examines the resource-allocation state to ensure that
there can never be a circular-wait condition. When should the algorithm be called?
Resource-allocation state is defined by the number of
available and allocated resources, and the maximum
demands of the processes.
System Model
5/28/2018 CENG334 2013 W06 Synchronization Monitors
55/65
55
Resource types R1, R2, . . ., Rm CPU,
memory, I/O devices
disk
network
Each resource type Rihas Wiinstances. For instance a quad-core processor has
4 CPUs
Each process utilizes a resource as follows:
request use
release
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Resource-Allocation Graph
5/28/2018 CENG334 2013 W06 Synchronization Monitors
56/65
56
V is partitioned into two types:
P= {P1, P2, , Pn}, the set consisting of all the
processes in the system.
R= {R1, R2, , Rm}, the set consisting of all
resource types in the system.
request edgedirected edge P1Rj
assignment edgedirected edge RjPi
A set of vertices Vand a set of edges E.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Resource Allocation Graph With A Deadlock
5/28/2018 CENG334 2013 W06 Synchronization Monitors
57/65
57
If there is a deadlock => there is acycle in the graph.
However the reverse is not true!
i.e. If there is a cycle in the graph=/> there is a deadlock
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Resource Allocation Graph With A Cycle But No Deadlock
5/28/2018 CENG334 2013 W06 Synchronization Monitors
58/65
58
However the existence of acycle in the graph does not
necessarily imply adeadlock.
Overall message:
If graph contains no cycles no deadlock.
If graph contains a cycle
if only one instance per resourcetype, then deadlock.
if several instances per resourcetype, possibility of deadlock.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Resource-Allocation Graph Algorithm
5/28/2018 CENG334 2013 W06 Synchronization Monitors
59/65
59
Claim edgePi->Rjindicated that process Pjmay
request resource Rj; represented by a dashed line.
Claim edge converts to request edge when a process
requests a resource.
When a resource is released by a process,
assignment edge reconverts to a claim edge.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Resource-Allocation Graph Algorithm
5/28/2018 CENG334 2013 W06 Synchronization Monitors
60/65
60
Claim edgePi->Rjindicated that process Pjmay
request resource Rj; represented by a dashed line.
Claim edge converts to request edge when a process
requests a resource.
When a resource is released by a process,
assignment edge reconverts to a claim edge.
Resources must be claimed a prioriin the system.
Note that the cycle detection algorithm does not work
with resources that have multiple instances.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Cycle => Unsafe
Safe, unsafe and deadlock states
5/28/2018 CENG334 2013 W06 Synchronization Monitors
61/65
61
If a system is in safe state =>no
deadlocks.
If a system is in unsafe state =>
possibility of deadlock.
Avoidance => ensure that a system will
never enter an unsafe state.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
Safe State
When a process requests an available resource system must
5/28/2018 CENG334 2013 W06 Synchronization Monitors
62/65
62
When a process requests an available resource, system must
decide if immediate allocation leaves the system in a safe state.
System is in safe state if there exists a safe sequence of all
processes.
Sequence is safe if for each Pi, the resources that
Pi can still request can be satisfied by currently available
resources + resources held by all the Pj, with j < i.
If Piresource needs are not immediately available, then Pican wait until all Pjhave
finished.
When Pjis finished, Pican obtain needed resources, execute, return allocated
resources, and terminate.
When Piterminates, Pi+1can obtain its needed resources, and so on.
Adapted from Operating System Concepts (Silberschatz, Galvin, Gagne) slides.
5/28/2018 CENG334 2013 W06 Synchronization Monitors
63/65
Example
5/28/2018 CENG334 2013 W06 Synchronization Monitors
64/65
64
29P2
24P1
510P0
Current NeedsMaximum NeedsThe system has threeprocesses and 12
tape drives.t=t0
The system at t0 is safe since the sequence exists.
Example
5/28/2018 CENG334 2013 W06 Synchronization Monitors
65/65
65
29P2
24P1
510P0
Current NeedsMaximum NeedsThe system has threeprocesses and 12 tape
drives.t=t0
The system at t1 is no longersafe since P1 requests 2 more tape drives, finishes and releases 4 drives.
However 4 drives are not sufficient for P0 or P2 complete its operation and wouldresult in a deadlock.
P2 requests one more drive
39P2
24P1
510P0
Current NeedsMaximum Needs
t=t1