Chapter 2Chapter 2
Processes and Scheduling(II)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual Exclusion and SynchronizationMutual Exclusion and Synchronization
Principles of concurrency.
Mutual Exclusion: Software approaches and Hardware
Support.
Semaphores 、 Monitors 、 Message Passing.
Tradition question:
Producer/Consumer 、 Readers/Writers Problem.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Difficulties Arise in Concurrency Difficulties Arise in Concurrency
Types: interleaving and overlapping.
The sharing of global resources is fraught with peril.
It is difficult for the OS to manage the allocation of resources optimally.
It is difficult to locate a programming error, because results are typically not reproducible.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Sharing can lead to problemsSharing can lead to problems
Process P1
.
input (in, keyboard)
.
out:=in
output (out, display)
.
.
Process P2
.
input (in, keyboard)
.
out:=in
output (out, display)
.
.
So, it is necessary to protect shared global variables.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Problems of ConcurrentProblems of Concurrent
Resource competition: How to allocate the resource,
and how to mutual exclusion access the critical
resources.
Execution sequence.
Communication cooperation.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Process Interaction (table5.1)Process Interaction (table5.1)
Processes unaware of each other: OS needs to be concerned about competition for resources. Exp. Two independent applications may both want access to the same disk or file or printer.
Processes indirectly aware of each other(e.g., shared object): The processes share access to some object such as I/O buffer.
Processes directly aware of each other: Communicate with each other by name.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual Exclusion(P193)Mutual Exclusion(P193)
Critical resource: Only one process can access it at a time.
Critical section : the portion of the program that uses critical resource.
entry sectioncritical section
exit section
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
P194 , fig5.1
Program mutualexclusion
Const n-…; (*num of processes)
Procedure P(i:integer)
Begin
repeat
enter critical(R)
<critical section>;
exit critical(R)
<remainder>
forever
End;
Begin(*main program*) parbegin p1; p2; … pn; parendEnd.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock and Starvation(P194)Deadlock and Starvation(P194)
Deadlock٭ Exp. Two processes P1 、 P2, both request to resource
R1 、 R2. At a time:٭ P1 gets R2 and P2 gets R1, in the meantime P1 requests
R1 and P2 requests R2٭ Then P1 and P2 wait for each other forever ---deadlock.
Starvation٭ P1 always communication with P2, p3 is starved.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Cooperation among Processes by Sharing(p195)Cooperation among Processes by Sharing(p195)
Data integrity
٭ Reading and writing, and only writing operations must be exclusive.
Data coherence: a=b no longer holds
P1: a:=a+1 b:=b+1P2: b:=2*b a:=2*a
a:=a+1b:=2*bb:=b+1a:=2*a
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Cooperation among Processes by CommunicationCooperation among Processes by Communication
Synchronize: The processes send and receive data between each other coordinately.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Requirements for Mutual Exclusion (Requirements for Mutual Exclusion ( 互斥互斥 )(P196)(P196 ))
Mutual exclusion must be enforced.
A process that halts in its noncritical section must do so without interfering with other processes.
It must not be possible for a process requiring access to a critical section to be delayed indefinitely.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Requirements for Mutual ExclusionRequirements for Mutual Exclusion
When no process is in a critical section, any process that requests entry to its critical section must be permitted to enter without delay.
No assumptions are made about relative process speeds or number of processors.
A process remains inside its critical section for a finite time only.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual Exclusion: Software ApproachesMutual Exclusion: Software Approaches
Dekker’s Algorithm
Peterson’s Algorithm
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm—First AttemptDekker’s Algorithm—First Attempt
Fig 5.2 An Igloo for Mutual Exclusion
٭ The entrance and the igloo itself are small enough that only one person can be in the igloo at a time. Inside, there is a blackboard on which a single value can be written.
٭ A process wishing to execute its critical section first enters the igloo and examines the blackboard.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm —First AttemptDekker’s Algorithm —First Attempt
If its number is on the blackboard, then the process may leave the igloo and proceed to its critical section. After has completed the critical section, it should place the number of the other process on the board
If not its number, it leaves the igloo and is forced to wait. From time to time, the process reenters the igloo to check the blackboard until it is allowed to enter its critical section. (busy waiting)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm —First AttemptDekker’s Algorithm —First Attempt
PROCESS 1
…
while turn ≠ 1 do {nothing};
<critical section>
turn:=0;
…
var turn:0..1;
PROCESS 0
…
while turn≠0 do {nothing};
<critical section>;
turn:=1;
…
Processes must strictly alternate in their use of their critical sections.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Second AttemptDekker’s Algorithm –Second Attempt
Fig5.3:A two-Igloo solution for mutual exclusion (P199)
Each process may examine the other’s board but cannot alter it.
When a process wishes to enter its critical section, it periodically checks the other’s board until it finds “FALSE” written on it, indicating that the other process is not in its critical section.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Second AttemptDekker’s Algorithm –Second Attempt
If false, writes “true” on its own board and enter. After finish, alter its board to show “false”
If true , busy waiting
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Second AttemptDekker’s Algorithm –Second Attempt
PROCESS 1
…
while flag[0] do {nothing};
flag[1]:=true;
<critical section>;
flag[1]:=false;
…
var flag : array [0..1] of boolean :false ;
PROCESS 0
…
while flag[1] do {nothing};
flag[0]:=true;
<critical section>;
flag[0]:=false;
…
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Second AttemptDekker’s Algorithm –Second Attempt
Analysis
Cannot guarantee mutual exclusion:
P0 : flag[1]=false; do while flag[1];
P1 : flag[0]=false; do while flag[0];
P0 : flag[0]=true; <critical section>;
P1 : flag[1]=true; <critical section>;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Third AttemptDekker’s Algorithm –Third Attempt
PROCESS 1
…
flag[1]:=true;
while flag[0] do {nothing};
<critical section>
flag[1]:=false;
…
var flag : array [0..1] of boolean : false;
PROCESS 0
…
flag[0]:=true;
while flag[1] do {nothing};
<critical section>;
flag[0]:=false;
…
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Third AttemptDekker’s Algorithm –Third Attempt
Analysis
P0 : set flag[0]=true;
P1 : set flag[1]=true;
P0 : do: while flag[1]; block ;P1 : do: while flag[0]; block ;=>causing deadlock
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Fourth AttemptDekker’s Algorithm –Fourth Attempt
PROCESS 1
…
flag[1]:=true;
while flag[0] do
begin
flag[1] :=false;
<delay for a short time>;
flag[1]:=true;
end;
<critical section>
flag[1]:=false;
…
PROCESS 0
…
flag[0]:=true;
while flag[1] do
begin
flag[0] :=false;
<delay for a short time>;
flag[0]:=true;
end;
<critical section>;
flag[0]:=false;
…
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –Fourth AttemptDekker’s Algorithm –Fourth Attempt
AnalysisP0 : set flag[0]=true; P1 : set flag[1]=true;P0 : do, while flag[1];P1 : do,while flag[0];P0 : set flag[0]=false; P1 : set flag[1]=false;P0 : set flag[0]=true; P1 : set flag[1]=true; ……Repeat this sequence forever, both process cannot enter
the critical section. (not deadlock)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –A Correct SolutionDekker’s Algorithm –A Correct Solution
Procedure P0;Begin repeat flag[0]:=true; while flag[1] do if turn=1 then begin flag[0]:=false; while turn=1 do {nothing} flag[0]:=true; end <critical section>; turn:=1; flag[0]:=false; <remainder> foreverEnd;
Procedure P1;Begin repeat flag[1]:=true; while flag[0] do if turn=0 then begin flag[1]:=false; while turn=0 do {nothing} flag[1]:=true; end <critical section>; turn:=0; flag[1]:=false; <remainder> foreverEnd;
Var flag:array[0..1] of boolean; turn:0..1;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –A Correct SolutionDekker’s Algorithm –A Correct Solution
Begin
flag[0]:=false;
flag[1]:=false;
turn:=1;
parbegin
P0; P1;
parend
end
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dekker’s Algorithm –A Correct SolutionDekker’s Algorithm –A Correct Solution
Analysis (P0 )Set flag[0]:=true;Do, while flag[1]
٭ false, P0 enters,when finish,set turn:=1; flag[0]:=false;٭ true, check value of turn
▪ 1,busy waiting▪ 0, P1 has finished (but has not modified flag), P0
enters
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Peterson AlgorithmPeterson Algorithm
Var flag:array[0..1] of boolean; turn: 0..1;
Procedure P0;Begin repeat flag[0]:=true; turn:=1; while flag[1] and turn =1 do {nothing} <critical section> flag[0]:=false; <remainder> foreverEnd;
Procedure P1;Begin repeat flag[1]:=true; turn:=0; while flag[0] and turn =0 do {nothing} <critical section> flag[1]:=false; <remainder> foreverEnd;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Peterson AlgorithmPeterson Algorithm
Begin
flag[0]:=false;
flag[1]:=false;
turn:=1;
parbegin
P0; P1;
parend
End.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Peterson AlgorithmPeterson Algorithm
Analysis
٭ Flag is used for who wants to enter.
٭ Turn is used to avoid deadlock.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual Exclusion: Hardware SupportMutual Exclusion: Hardware Support
Interrupt Disabling
٭ Only suitable for single processor, and the efficiency of
execution is degraded.
Special Machine Instructions : These actions are performe
d in a single instruction cycle, they are not subject to inter
ference from other instrcutions.
٭ Test and Set
٭ Exchange Instruction
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Test and Set (P205)Test and Set (P205)
function testset ( var i:integer ) : boolean ; begin if i = 0 then begin i := 1; testset := true; end else testset :=false; end.
Notes: when i=0 presents resource is free. When i=1 presents resource is used ,
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Application(fig 5.7a)Application(fig 5.7a)
program mutualexclusion;const n= …; (*number of processes*);var bolt: integer;procedure P( i:integer);begin repeat repeat {nothing} until testset(bolt); <critical section> bolt:=0; <remainder> foreverend;
begin (*main program*) bolt:=0; parbegin p(1); p(2); …… p(n); parendend.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exchange(P205)Exchange(P205)
procedure exchange ( var r :register; var m :memory );var temp;begin temp := m; m := r; r := temp;end.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Application (Fig5.7b)Application (Fig5.7b)
program mutualexclusion
const n=…; (*number of processes*);
var bolt: integer;
procedure P(i:integer)
var keyi: integer;
begin
repeat
keyi:=1;
repeat exchange (keyi, bolt) until keyi=0;
<critical section>
exchange(keyi, bolt);
<remainder>
forever
end;
begin (*main program*) bolt:=0; parbegin p(1); p(2); …… p(n); parendend.
nkeybolti
i
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Characteristics of Hardware Command (P207)Characteristics of Hardware Command (P207)
Adv. Simple Be suitable for multi-processes to share memory in single
process or multi processors environment Be suitable for accessing multi-critical sections. Every cri
tical section can define a variable.
Disadv. Busy for waiting Maybe induce hungry Maybe induce deadlock. Exp, when a process, which is in
a critical section, is interrupted, then deadlock happens……
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Semaphores (OS provide)Semaphores (OS provide)
Function: Be used to implement mutual exclusion and synchronization
Operations of semaphore: Assuming the semaphore is a integer
• Semaphore can be initialed as a no-negative integer
• wait(s): s - 1; if s < 0, block the correspondent process
• signal(s): s + 1; if s≤0, wakeup the correspondent process
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Types of SemaphoreTypes of Semaphore
General semaphore: Fig5.8
Binary semaphore: Fig5.9
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
F5.8 A Definition of Semaphore PrimitivesF5.8 A Definition of Semaphore Primitives
Type semaphore= recordcount: integerqueue:list of process –FCFS
end;Var s: semaphore
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Wait(s): s.count=s.count-1; if s.count<0 then begin
place this process in s.queue;block this process
end;
Signal(s): s.count:=s.count+1; if s.count <=0 then begin remove a process P from s.queue; place process P on ready list end
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
F5.9 A Definition of Binary Semaphore PrimitivesF5.9 A Definition of Binary Semaphore Primitives
Typebinary semaphore= record
value:(0,1)
queue:list of process –FCFS
end;
Var s: binary semaphore;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Binary SemaphoreBinary Semaphore
WaitB(s):
if s.value=1 then s.value:=0
else begin
place this process in s.queue;
block this process
end;
SignalB(s):
if s.queue is empty then s.value :=1
else begin
remove a process P from s.queue;
place process P on ready list
end
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
SemaphoreSemaphore
Wait 、 signal are primitive operations
Wait operation request resources and maybe block the requestor. Signal operation release resources and maybe wakeup the blocked process.
General semaphore is a record. It is composed of an integer and a list of block processes which wait for the resources presented by the semaphore (FIFO) .
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual Exclusion by Semaphore (Fig5.10)Mutual Exclusion by Semaphore (Fig5.10)
Program mutualexclusionConst n=…;//number of processe
sVar s:semaphore(:=1);Procedure P(i:integer);Begin repeat wait(s); <critical section> signal(s); <remainder> foreverEnd;
Begin //main program parbegin P1; P2; …. Pn; parendEnd.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Significance of SemaphoreSignificance of Semaphore
1. Mutual exclusion semaphore: request/release the privilege, initial value is 1
2. Resource semaphore: request/release resource , initial value s.count =n (n>0) (presents the number of the resources )٭ s.count≥0:is the number of processes that can execute wait
(s) without suspension.٭ s.count 0: the number of processes suspended in s.queue﹤
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
The Producer/Consumer Problem (P211)The Producer/Consumer Problem (P211)
Description:
٭ Producer: One or more producers generate data and put the data into buffer
٭ Consumer: Only one consumer get the data from buffer Limited:
٭ Buffer can be accessed only by a process(producer or consumer) at a time(mutual exclusion).
٭ Control producer/Consumer access buffer in a rational sequence. Producer could not write data to a full buffer and consumer could not read data from a empty buffer.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Infinite-BufferInfinite-Buffer
producer : consumer :repeat repeat
produce item v; while in≤out do {nothing};
b[in] := v; w := b[out];
in := in + 1 ; out := out + 1 ;forever; consume item w;
forever;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
An Incorrect Solution to the Infinite-Buffer P/C Problem An Incorrect Solution to the Infinite-Buffer P/C Problem Using Binary Semaphore(Fig5.13)Using Binary Semaphore(Fig5.13)
Program producerconsumerVar n:=0 integer; s:(*binary*)semaphore(:=1) delay:(*binary*)semaphre(:=0)Procedure producerBegin repeat produce; waitB(s); append; n:=n+1; if n=1 then signalB(delay); signalB(s); foreverEnd;
Procedure consumer;Begin waitB(delay); repeat waitB(s); take; n:=n-1; signalB(s); consume; if n=0 then waitB(delay) forever
End;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Incorrect SolutionIncorrect Solution
Begin (*main program*)
n:=0;
parbegin
producer; consumer;
parend;
End.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Incorrect SolutionIncorrect Solution
action n delay
1 initially 0 0
2 Producer:critical section 1 1
3 Consumer: waitB(delay) 1 0
4 Consumer:critical section 0 0
5 Producer:critical section 1 1
6 Consumer:if n=0 then waitB(delay) 1 1(not do)
7 Consumer:critical section 0 1
8 Consumer:if n=0 then waitB(delay) 0 0
9 Consumer:critical section -1 0
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Incorrect SolutionIncorrect Solution
If simply to move the conditional statement inside the critical section of the consumer, will lead deadlock.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock May OccurDeadlock May Occur
Program producerconsumerVar n: integer; s:(*binary*)semaphore(:=1) delay:(*binary*)semaphre(:=0)Procedure producerBegin repeat produce; waitB(s); append; n:=n+1; if n=1 then signalB(delay); signalB(s); foreverEnd;
Procedure consumer;Begin waitB(delay); repeat waitB(s); take; n:=n-1;
if n=0 then waitB(delay) signalB(s); consume; foreverEnd.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Correct Solution (auxiliary variable)Correct Solution (auxiliary variable)
Program producerconumerVar n: integer; s:(*binary*)semaphore(:=1) delay:(*binary*)semaphre(:=0)Procedure producerBegin repeat produce; waitB(s); append; n:=n+1; if n=1 then signalB(delay); signalB(s); foreverEnd;
Procedure consumer;Var m:integer;(* a local variable*)Begin waitB(delay); repeat waitB(s); take; n:=n-1; m:=n; signalB(s); consume; if m=0 then waitB(delay) foreverEnd;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Correct Solution (auxiliary variable)Correct Solution (auxiliary variable)
n = in – out ; S is the mutual exclusion semaphore for accessing buffe
r; delay is resource semaphore
Problem: waitB(delay) and signalB(delay) not matching (Table5.2)
Solution: add a auxiliary variable , Fig5.14
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
A Solution to the Infinite-Buffer P/C Problem A Solution to the Infinite-Buffer P/C Problem Using Semaphores(F5.15Using Semaphores(F5.15 ))
Procedure producer
Begin
repeat
produce;
wait(s);
append;
signal(s);
signal(n);
forever
End;
Procedure consumer;Begin repeat
wait(n);wait(s);take;signal(s);consume;
foreverEnd;
Program producerconsumerVar n:semaphore(:=0)
s:semaphore(:=1)
Note the sequence
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Solution of Finite-BufferSolution of Finite-Buffer
Define of producer and consumer (P214 )
Use general semaphore to solution finite-buffer P/C problem (F5.17 , P218 )
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Program boundedbufferProgram boundedbufferconst sizeofbuffer=…;const sizeofbuffer=…;
var s:semaphore(:=1); n:semaphore(:=0); var s:semaphore(:=1); n:semaphore(:=0); e:semaphore(:=sizeofbuffer); e:semaphore(:=sizeofbuffer);
Procedure producer;
Begin
repeat
produce;
wait(e);
wait(s);
append;
signal(s);
signal(n);
forever
End;
Procedure consumerBegin repeat wait(n); wait(s); take; signal(s); signal(e); consume forever;End;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Implementation of Semaphores p215Implementation of Semaphores p215
Wait and signal operations must be implemented as atomic primitives.
How to realize:
٭ Hardware or firmware(p219 F5.18)
٭ Dekker’s or Peterson’s algorithm
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
F5.18 F5.18
Wait(s):
Repeat {nothing} until testset (s.flag)
// or inhibit interrupts
s.count:=s.count-1;
if s.count <0
then begin
place this process in s.queue;
block this process (must also set s.flag to 0 // or allow interrupts)
end
else s.flag :=0; //or allow interrrupts
signal(s):
Repeat {nothing} until testset (s.flag)
// or inhibit interrupts
s.count:=s.count+1;
if s.count <=0
then begin
remove a process from s.queue;
place this process on ready list
end;
s.flag :=0; //or allow interrupts
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Conclusion of Mutual Exclusion and SynchronizationConclusion of Mutual Exclusion and Synchronization
Using wait 、 signal primitive action to implement.
Software methods, e.g. Dekker algorithm 、 Peterson algorithm (need spending of processor).
Hardware methods, e.g. interrupt disabling 、 Test and Set etc.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Barber Problem (p216Barber Problem (p216 ))
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Barber Problem--initBarber Problem--init
Program barbershop1;
Var max_capacity: semaphore(:=20);
sofa: semaphore(:=4);
barber_chair, coord: semaphore(:=3);
cust_ready, finished: semaphore(:=0);
leave_b_chair, payment: semaphore(:=0);
receipt: semaphore(:=0);
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Barber ProblemBarber Problem
Wait(max_capacity) enter shop; wait(sofa); sit on sofa; wait(barber_chair); get up from sofa; signal(sofa) sit in barber chair; signal (cust_ready); wait(finished); leave barber chair; signal(leave_b_chair); pay; signal (payment); wait(receipt); exit shopSignal(max_capacity)
Customer Barber
repeat wait(cust_ready); wait(coord); cut hair; signal(coord); signal(finished); wait(leave_b_chair); signal(barber_chair);forever
Cashier
Repeat wait(payment); wait(coord); accept pay; signal(coord); signal(receipt);forever
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
winsdk – examples for mutual exclusion winsdk – examples for mutual exclusion
HANDLE CreateThread (…)
HANDLE CreateEvent(…)
HANDLE CreateMutex( …)
DWORD WaitForSingleObject( HANDLE hHandle, // 等待对象的句柄 DWORD dwMilliseconds // 等待毫秒数, INFINITE 表示无限等待 );
int main(…){evtGet = CreateEvent(NULL, FALSE, TRUE, “GetResult"); CreateThread(NULL, 0, &BubbleSort, &StructData1, NULL, &TID1); CreateThread(NULL, 0, &SelectSort, &StructData2, NULL, &TID2); }void PrintResult( …){WaitForSingleObject(evtGet, INFINITE); // 等待事件有信号 ……SetEvent(evtGet); // 把事件信号量恢复,变为有信号 }
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
winsdk – examples for mutual exclusion (II)winsdk – examples for mutual exclusion (II)
unsigned long __stdcall BubbleSort(void* theArray)
{
……
PrintResult(Array, iLength, “Bubble Sort”); // 取排序结果 ……
}
unsigned long __stdcall SelectSort(void* theArray)
{
……
PrintResult(Array, iLength, "Select Sort");
……
}
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Monitor——OO MethodMonitor——OO Method
It is not simple to use semaphore to implement synchronization (the sequence and location of wait 、 signal operations is important).
Monitor is the programs written by pascal 、 pascal plus 、 Modula-2 、 Modula-3 languages. Monitor can lock any objects such as list or elements in a list.
Using monitor is simple than using semaphore to implement synchronization.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
MonitorMonitor
The monitor is a programming-language construct that
provides equivalent functionality to that of semaphore but
is easier to control.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Monitor with Signal (p224)Monitor with Signal (p224)
The local data variables are accessible only by the monitor’s procedures and not by any external procedure.
A process enters the monitor by invoking one of its procedure.
Only one process may be executing in the monitor at a time; any other process that has invoked the monitor is suspended, waiting for the monitor to become available.
The data variables in the monitor can be accessed by only one process at a time.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Using a Monitor for P/C problemUsing a Monitor for P/C problem
program producerconsumermonitor boundedbuffer;
buffer: array[0..N] of char; //space for N itemsnextin, nextout: integer; //buffer pointercount: integer; //number of items in buffernotfull, notempty: condition //for synchronization
procedure append (x:char)begin
if count = N then cwait(notfull); //avoid underflowbuffer[nextin]:= x;nextin := nextin+1 mod N;count := count +1;csignal(notempty); //resume consume
rend;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Monitor with SignalMonitor with Signal
procedure take (x:char)
begin
if count = 0 then cwait(notempty); //avoid underflow
x:= buffer[nextout];
nextout := nextout+1 mod N;
count := count -1;
csignal(notfull); //waiting producer
end;
Begin
nextin:=0; nextout:=0; count:=0 //initally
End;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Monitor with SignalMonitor with Signal
procedure producer;
var x: char;
begin
repeat
produce(x);
append(x);
forever
end;
procedure consumer;
var x: char;
begin
repeat
take(x);
consume(x);
forever
end;
Begin //main programparbegin
producer;consumer;
parend
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Message Passing(p230)(Message Passing(p230)( 消息传递消息传递 ))
To implement synchronization (同步) and communication (通信) of processes
Primitive action (原子操作) of message passing
٭ send( destination (目标), message)
٭ receive( source (源), message)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Types of SynchronizationTypes of Synchronization (( p231p231 ))
Sender (发送者) : After sending a message, if or not blocks( 阻塞 ) to wait for ACK (确认) message?
Receive (接收者) : If not receive the msg from sender, block or not block to wait for the msg?
Types Blocking send, blocking receive: rendezvous (汇合) Nonblocking (非阻塞) send, blocking receive. Nonblocking send, nonblocking receive.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Addressing (p232)Addressing (p232) (寻址)(寻址)
Direct addressing (直接寻址) by ID of process Indirect addressing( 间接寻址 ): share data area (list 、
mailbox) Relationship (对应关系) of sender and receiver :
٭ One to one (一对一) : e.g.( 例如 ) private mailbox(私有信箱)
٭ Many to one (多对一) : e.g. client/server (客户 /服务模式)
٭ One to many (一对多) : e.g. Broadcast (广播)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Association(Association( 关系关系 ) of Process and Mailbox) of Process and Mailbox (( p233p233 ))
Static (static port ) ( 静态端口 ) : e.g. one to one Dynamic( 动态 ) : (multi-sender, connect/ disconnect )
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Message Format (Message Format ( 消息格式消息格式 )) (( p234p234 ))
Fix Length (定长) : Minimize processing and storage over
head (负荷) .
Variable Length (变长) : Header + Body, fig5.25
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Message Queuing Discipline (Message Queuing Discipline ( 消息队列结构 消息队列结构 p234)p234)
FIFO
Queue by priority (优先权队列)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual Exclusion (Mutual Exclusion ( 互斥互斥 p234)p234)
Assuming nonblocking send, blocking receive.
Many processes share (共享) a mailbox needing mutual exclusion.
٭ A process wishing to enter its critical section (临界区) first attempts (希望) to receive a message.
٭ If the mailbox is empty, then the process is blocked;
٭ Once a process has acquired (获得) the message, it performs its critical section and then places the message back into the mailbox.
٭ Thus, the message functions as a token (令牌) that is passed from process to process.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Program mutual exclusionConst n= …;(*number of processes*)Procedure p(i:integer)Begin
repeatreceive (mutex, msg);<critical section>send (mutex, msg);<remainder>
foreverEnd;
Mutual Exclusion (p235)Mutual Exclusion (p235)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Mutual ExclusionMutual Exclusion
Begin(*main program)create_mailbox(mutex);send(mutex, null);parbegin
p(1);p(2);…p(n);
parendend
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Using Messages to Solution P/C Problem (Fig 5.27)Using Messages to Solution P/C Problem (Fig 5.27)
Two mailbox:
٭ Mayconsume: presents (表示) producer has put the data in buffer and consumer should get from it.
٭ Mayproduce: presents the buffer is empty for save data sent from producer.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Const capacity=…; {buffering capacity}
null=…;{empty message}
Var i: integer;
Procedure producer;
Var pmsg: message;
begin
while true do
begin
receive(mayproduce,pmsg);
pmsg:=produce;
send(mayconsume,pmsg);
end;
end;
Procedure consumer;Procedure consumer; var csmg:message;var csmg:message; beginbegin while true dowhile true do beginbegin
receive (mayconsume,cmsg)receive (mayconsume,cmsg)consume(csmg)consume(csmg)send(mayproduce,nullsend(mayproduce,null))
endend endendBeginBegin create_mailbox(mayproduce);create_mailbox(mayproduce); create_mailbox(mayconsume);create_mailbox(mayconsume); for i=1 to capacity do for i=1 to capacity do
send(mayproduce,null);send(mayproduce,null); parbeginparbegin producer;producer; consumers;consumers; parendparendEnd;End;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Readers/Writers ProblemReaders/Writers Problem (读者(读者 // 写者问题写者问题 p237p237 ))
Description( 描述 ):
٭ Many processes share a data area (file 、 memory area 、 a group of registers etc.). The reader process can read data and the write process can write data.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Readers/Writers ProblemReaders/Writers Problem
Condition (条件) :
• Allow many readers read a share area at the same time;
• Not allow many writers to write a share area at the same time;
• If a writer is writing a share area, the readers can not access the same area.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Readers Have PriorityReaders Have Priority (读者优先(读者优先 p238p238 ))
When a reader is reading a data, allow other readers who reach later to enter. So a writer may starve (饥饿) when readers is many.
Using semaphore to solution the Reader/writer problems. Fig5.28
٭ Wsem: Using for realizing mutual exclusion between first reader and writer, and between writer and writer.
٭ Readcount: Calculate how many readers are reading data.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Program readerandwriters;Var readcount:integer;x,wsem:semaphore(:=1);Procedure reader;Repeat wait(x); readcount:=readcount+1; if readcount=1 then wait(wsem); signal(x); READUNIT; wait(x); readcount=readcount-1; if readcount=0 then signal(wsem); signal(x);forever
Procedure writer;Repeat wait(wsem); WRITEUNIT; signal(wsem)forever
Begin(*main program*) readcount:=0; parbegin reader; writer; parend
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Writers Have PriorityWriters Have Priority (写者优先(写者优先 p239p239 ))
When a writer wish to write data, the new reach reader is not allowing to read.
Fig 5.29
Rsem: Not allowing new reach reader to enter.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Program readerandwriters;Program readerandwriters;var readcount, writecount:integer;var readcount, writecount:integer; x,y,z,wsem,rsem:semaphore(:=1); x,y,z,wsem,rsem:semaphore(:=1);
Procedure readerRepeat wait(z); wait(rsem); wait(x); readcount:=readcount+1; if readcount=1 then wait(wsem) signal(x); signal(rsem); signal(z); readunit;Wait(x) readcount:=readcount –1; if readcount=0 then signal(wsem);Signal(x)forever;
Procedure writer;Repeat wait(y); writecount:=writecount+1; if writecount=1 then wait(rsem) signal(y); wait(wsem) writeunit; signal(wsem); wait(y); writecount:=writecount-1; if writecount=0 then signal(rsem) signal(y);forever
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Readers only in the system wsem setno queues
Writes only in the system wsem and rsem setwriters queue on wsem
Both reader and writer with wsem set by readerRead first rsem set by writer
all writers queue on wsemone reader queues on rsemother readers queue on z
Both readers and writers wsem set by writerWith write first rsem set by writer
writers queue on wsemone reader queues on rsemother readers queue on z
Table 5.5 P239
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
小结:小结: P/C vs.(P/C vs.( 对比对比 ) R/W ) R/W
Producer/Consumer:
٭ Synchronization problem.
٭ Producer and consumer access a share area according a rule.
Readers/Writers:
٭ Mutual exclusion problem.
٭ If writer in , all readers cannot in.
٭ If one of the readers in , the writer cannot in.
٭ Only one writer can in at the same time.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Use Semaphore to Realize Mutex and SynchronizationUse Semaphore to Realize Mutex and Synchronization
Semaphore s:=1;
P1/P2/…/Pn()
{ …..
Wait(s)
Critical section
Signal(s)
…..
}
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Use Semaphore to Realize SynchronizationUse Semaphore to Realize Synchronization
Semaphore s1:=1, s2=0 P1() P2(){… {…. wait(s1) wait(s2) share(com)_section share(com)_section signal(s2) signal(s1) …} …}
Question:٭ if s1=0,s2=0, how to modify the code?
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock and StarvationDeadlock and Starvation (死锁和饥饿 (死锁和饥饿 P253P253 ))
Content
The reasons for deadlock and starvation
The methods for solution the deadlock
Dining philosophers problem
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Principles of DeadlockPrinciples of Deadlock (死锁概念)(死锁概念)
Deadlock: The permanent (永久) blocking of a set of
processes that either compete (竞争) for system resou
rces or communicate with each other.
Exp: Deadlock for traffic fig6.1 solution: red/green light
(and semaphore ) Process deadlock: Fig6.2
Execute sequence: Fig6.4
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Reusable ResourcesReusable Resources (p256)(p256)
Type of resource
٭ Reusable resource (可重用资源) : Can be safely used by only one process at a time and is not depleted(耗尽) by that use. E.g. processors 、 I/O channel( 通道 ) and device 、 main and secondary memory, devices and data structures such as files 、 database 、semaphores.
٭ Deadlock may happen when processes compete the reusable resource: Fig6.4
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Example of DeadlockExample of Deadlock (( p257p257 ))
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Consumable ResourcesConsumable Resources (消耗性资源(消耗性资源 p258p258 ))
Consumable Resources: Can be created and destroyed.
There is no limit on the number of consumable resource
s of a particular type, such as interrupts signals 、 mess
ages 、 information in I/O buffers.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exp (P258Exp (P258 ))
Total memory is 200k
P1
. . .
. . .
Request 80K bytes;
Request 60K bytes;
P2
. . .
. . .
Request 70K bytes;
Request 80K bytes;
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exp(P258Exp(P258 ))
Blocking receive (阻塞接收) will introduce deadlock.
P1
. . .
. . .Receive(P2);
Send(P2, M1);
P2
. . .
. . .Receive(P1);
Send(P1, M2);
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
The Conditions for Deadlock (p258The Conditions for Deadlock (p258 ))
Mutual exclusion
Hold and Wait (持有且等待) No Preemption (不抢占) Circular Wait (循环等待)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Circular WaitCircular Wait (( p260p260 ))
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
The Solution to DeadlockThe Solution to Deadlock (解决死锁)(解决死锁)
Prevention (预防) Avoidance (避免) Detection and recovery (检测和恢复) pp259 table6.1 (总结表)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock Prevention(Deadlock Prevention( 预防死锁预防死锁 p260)p260)
Indirect method (间接方法) , to prevent the occurrence of one of the three necessary conditions:
• Mutual exclusion: Can not be disallowed. Must be supported by the OS (example: fwrite(…)).
• Hold and wait:
• A process request all of its required resource at one time and blocking the process until all requests can be granted simultaneously (同时分配) (example: red-green light).
• If a process holding (持有) certain resources is denied (禁止) another request.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock PreventionDeadlock Prevention
No preemption( 非抢占 ) :• If a process requests a resource that is held by a
nother process, the OS may preempt the second process and require it to release its resource (resources whose state can be easily saved and restored later, as is the case with a processor).
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock PreventionDeadlock Prevention
Direct method (直接方法), to prevent the occurrence of a circular wait:
٭ Defining a linear ordering of resource types (资源按类型线性排序) . If a process has been allocated resources of type R, then it may subsequently request only those resources of types following (后继) R in the ordering.
٭ Inefficient (低效) , slowing down processes execution.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock Avoidance(Deadlock Avoidance( 避免死锁避免死锁 p262)p262)
Prevent deadlock leads to inefficient use of resources and inefficient execution of processes. Avoid deadlock a decision is made dynamically( 动态地 ) whether the current resource allocation request will potentially (可能) lead to a deadlock.
The approaches to deadlock avoidance:
• Do not grant (分配) an incremental resource request to a process if this allocation might lead to deadlock.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Safe StateSafe State (安全状态(安全状态 p263p263 ))
If OS executes processes in order such as <P1 , P2 ,…, Pn> ( refer <P1 , P2 ,…, Pn> as safe sequence) to allocate resource , and every process can get its maximum requests and complete. Then a system is in safe state.
If can not find a safe sequence in system, then the system is in unsafe state.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Safe StateSafe State
If a system is in unsafe state, it may not be deadlock. But it may enter a deadlock state.
If a system is in safe state, It must not be deadlock.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
From Safe to Unsafe State(From Safe to Unsafe State( 补充例子补充例子 ))
There are three process P1 、 P2 、 P3,12 printer. P1 needs 10 printer, P2 and P3 need 4 and 9. At T0, P1 、 P2 、 P3 has held 5 、 2 、 2, and still 3 printer free.
process max allocated available
P1 10 5 3
P2 4 2
P3 9 2
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
From Safe to UnsafeFrom Safe to Unsafe
At t0 the system is safe, because there is a safe sequence<P2 , P1 , P3>.
But, if at t1, P3 get one more printer, and system has 2 printer free, the system is unsafe.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exp. of Safe State(p264)Exp. of Safe State(p264)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exp. of Safe StateExp. of Safe State
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exp. of Unsafe State(p265)Exp. of Unsafe State(p265)
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Banker’s Algorithm(Banker’s Algorithm( 银行家算法银行家算法 p267)p267)
type state=record
resource, available: array[0…m-1] of integer;
claim, allocated: array[0..n-1, 0..m-1] of integer;
endif alloc[i,*]+request[i,*] >claim[i,*] then <error> -total request >claimelse if request[i,*] >available[*] then <suspend process> else -simulate allocation <define newstate by: allocation[i,*]:= allocation[i,*] +request[i,*] available[*]:=available[*]-request[i,*]> end; if safe (newstate) then <carry out allocation> else <restore original state, suspend process > endend.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Banker’s AlgorithmBanker’s Algorithm (( IIII ))function safe(state:S):boolean;var currentavail: array[0..m-1] of integer;
rest: set of process;begin
currentavail:=available;rest:=[all processes];possible:=true;while possible do find a Pk in rest such that
claim[k,*]- alloc[k, *] <= currentavail; if found then ----simulate execution of p
currentavail :=currentavail +allocation[k,*]rest:=rest-[Pk]
elsepossible :=false
endend
safe:=(rest=null)end
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
RestrictionsRestrictions (限制) (限制) of Using Deadlock Avoidance (p26of Using Deadlock Avoidance (p266)6)
The maximum resource requirement for each process must be stated in advance (提前) .
The processes under consideration must be independent(进程的执行序是独立的) ; that is, the order in which they execute must be unconstrained by any synchronization requirements.
There must be a fixed number of resources to allocate.
No process may exit while holding resources.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Deadlock DetectionDeadlock Detection (检测(检测 p267p267 ))
Not limit resource access or process actions. Periodically, the OS performs (执行) an algorithm that allows it to detect the circular-wait condition.
Fig6.9
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Detection AlgorithmP268 Detection AlgorithmP268
1. Mark each process that has a row in the Allocation matrix( 矩阵 ) of all zero.
2. Initialize a temporary vector W to equal the Available vector.
3. Find an index i such that process i is currently unmarked and the ith row of Q( 请求 ) is less than or equal to W. That is Qik<=Wk, for 1<=k<=m, If no such row is found, terminate the algorithm.
4. If such a row is found, mark process i and add the corresponding row of the allocation matrix to W. That is Wk=Wk+Aik, Return to step 3.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
p268
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
p268p268
1. Mark P4, because P4 has no allocated resources.
2. Set W=(0 0 0 0 1).
3. The request of process P3 is less than or equal to W, so mark P3 and set W=W+(0 0 0 1 0)= (0 0 0 1 1).
4. Terminate the algorithm.
5. The algorithm concludes with p1 and p2 unmarked, indicating that these processes are deadlocked.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Recovery(Recovery( 恢复恢复 p269)p269)
1.Abort (终止) all deadlocked processes.
2.Back up each deadlocked process to some previously defined checkpoint (检查点) , and restart all processes.
3.Successively (连续的) abort deadlocked processes until deadlock no longer exists. The order in which processes are selected for abortion (终止) should be on the basis of some criterion (标准) of minimum cost.
4.Successively preempt resources until deadlock no longer exists.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Recovery(p269)Recovery(p269)
3 、 4 need to select a process:
٭ Least( 最少 ) amount of processor time consumed so far.
٭ Least amount of output produced so far
٭ Most estimated time remaining.
٭ Least total resources allocated so far.
٭ Lowest priority.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
An Integrated(An Integrated( 综合综合 ) Deadlock Strategy(p269)) Deadlock Strategy(p269)
Group resources into a number of different resource classes (资源分组) .
Use the linear ordering strategy for prevention of circular wait to prevent deadlocks between resource classes(资源类线性编号) .
Within a resource class, use the algorithm that is most appropriate (适合) for that class.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
An Integrated Deadlock Strategy(II)An Integrated Deadlock Strategy(II)
As an example, consider (思考) the following classes of resources:٭ Swappable (交换) space: Blocks of memory on second
ary storage for use in swapping processes. (Prevention deadlock by requiring all )
٭ Process resource: Resources that process needs. (Avoidance deadlock).
٭ Main memory: Assignable (可分配) in pages or segments to processes. ( Prevention deadlock by preempt).
٭ Internal resource: Such as I/O channels. ( Prevention deadlock by resource ordering).
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dining Philosophers(Dining Philosophers( 哲学家哲学家 ) Problem) Problem (( p270p270 ))
Five philosophers. The life of each philosopher consiste
d of thinking and eating. A round table on which was s
et a large serving bowl of spaghetti, each philosopher h
as a plate and a fork. A philosopher wishing to eat wou
ld use the two forks on either side of the plate ( 盘子) .
Devise (设计) a algorithm that will allow the philos
opher to eat. The algorithm must satisfy mutual exclusi
on while avoiding deadlock and starvation.
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Dining Philosophers ProblemDining Philosophers Problem
Using semaphore to solution the problem (may be deadlock and starvation Fig6.11 )
A solution: Only allows four philosophers at a time t
o eat. With at most four seated philosophers, at least one will have access to two forks.F6.12
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
program diningphilosophersvar fork: array[0..4] of semaphore(:=1);
i:integer;procedure philosopher (i:integer)begin repeat
think; wait(fork[i]); wait(fork[(i+1)mod 5]); eat; signal(fork[(i+1)mod 5]); signal(fork[i]);
foreverend;begin parbegin philosopher(0); philosopher(1); philosopher(2);
philosopher(3); philosopher(4); parendend
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
program diningphilosophersvar fork: array[0..4] of semaphore(:=1);
room: semaphore(:=4);i:integer;
procedure philosopher (i:integer)begin repeat
think; wait(room); wait(fork[i]); wait(fork[(i+1)mod 5]); eat; signal(fork[(i+1)mod 5]); signal(fork[i]); signal(room);
foreverend;begin parbegin philosopher(0); philosopher(1); philosopher(2);
philosopher(3); philosopher(4); parendend
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
ConclusionConclusion
Process Description and Control٭ Sequence execution and concurrence
execution٭ 2-states and 5-states model٭ Reasons of state transition٭ Process image٭ PCB٭ Kernel function
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
Exp.Exp.
System call -- FORK()
٭ How to implement a system call
٭ The procedure of create a process
٭ How to analysis kernel
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
ConclusionConclusion
Process Description and Control٭ Process Switch and Mode Switch٭ Create and destroy٭ Block and wakeup٭ Suspend and active٭ Reasons for introduce thread٭ Thread states and types٭ Thread and process
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
ConclusionConclusion
Mutual Exclusion and Synchronization
٭ Concurrence of processes exectuion
▪ critical resource
▪ critical section
▪ Condition of Mutual exclusion
PROCESSES AND SCHEDULINGPROCESSES AND SCHEDULING
ConclusionConclusion
٭ Software and hardware methods to realize mutual exclusion
٭ Semaphore 、 monitor and message passing
٭ Producer/consumer 、 reader/writer Deadlock And Starvation
٭ Reason for deadlock and starvation
▪ the conditions for deadlock
٭ Solution for deadlock
٭ Dining philosophers problem