3.process Synchronization
3.process Synchronization
Background
The Critical-Section Problem
Synchronization Hardware
Semaphores
Classic Problems of Synchronization
Monitors
Synchronization Examples
Atomic Transactions
Operating System Concepts – 7th Edition, Feb 8, 2005 6.2 Silberschatz, Galvin and Gagne ©2005
Background
Operating System Concepts – 7th Edition, Feb 8, 2005 6.3 Silberschatz, Galvin and Gagne ©2005
Producer
while (true) {
Operating System Concepts – 7th Edition, Feb 8, 2005 6.4 Silberschatz, Galvin and Gagne ©2005
Consumer
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
Operating System Concepts – 7th Edition, Feb 8, 2005 6.5 Silberschatz, Galvin and Gagne ©2005
Race Condition
count++ could be implemented as
register1 = count
register1 = register1 + 1
count = register1
count-- could be implemented as
register2 = count
register2 = register2 - 1
count = register2
Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = count {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = count {register2 = 5}
S3: consumer execute register2 = register2 - 1 {register2 = 4}
S4: producer execute count = register1 {count = 6 }
S5: consumer execute count = register2 {count = 4}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.6 Silberschatz, Galvin and Gagne ©2005
General Structure of Typical Process Pi
do
{
Entry Section
Critical Section;
Exit Section
Reminder Section;
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.7 Silberschatz, Galvin and Gagne ©2005
Typical Process Pi
1. Entry Section:
Each process must request permission to enter its critical
section. The section of code implementing this request is said to
be “Entry Section”
2. Critical Section:
The section of code which is shared between 1 or more
processes which may cause Race condition is said to be “Critical
Section”
3. Exit Section:
The critical section is followed by the “Exit section”.
4. Reminder Section:
The remaining code is the “Reminder Section”
Operating System Concepts – 7th Edition, Feb 8, 2005 6.8 Silberschatz, Galvin and Gagne ©2005
Solution to Critical-Section Problem
Operating System Concepts – 7th Edition, Feb 8, 2005 6.9 Silberschatz, Galvin and Gagne ©2005
Synchronization Hardware
Many systems provide hardware support for critical section
code
Uniprocessors – could disable interrupts
Currently running code would execute without
preemption
Generally too inefficient on multiprocessor systems
Operating systems using this not broadly scalable
Modern machines provide special atomic hardware
instructions
Atomic = non-interruptable
Either test memory word and set value
Or swap contents of two memory words
Operating System Concepts – 7th Edition, Feb 8, 2005 6.10 Silberschatz, Galvin and Gagne ©2005
TestAndSet Instruction
Definition:
Operating System Concepts – 7th Edition, Feb 8, 2005 6.11 Silberschatz, Galvin and Gagne ©2005
Solution using TestAndSet
while (true) {
while ( TestAndSet (&lock ))
; /* do nothing
// critical section
lock = FALSE;
// remainder section
Operating System Concepts – 7th Edition, Feb 8, 2005 6.12 Silberschatz, Galvin and Gagne ©2005
Swap Instruction
Definition:
Operating System Concepts – 7th Edition, Feb 8, 2005 6.13 Silberschatz, Galvin and Gagne ©2005
Solution using Swap
Shared Boolean variable lock initialized to
FALSE; Each process has a local Boolean
variable key.
Solution: Process-1
while (true)
Process-2:
{ while (true)
key = TRUE; {
while ( key == TRUE) key = TRUE;
Swap (&lock, &key ); while ( key == TRUE)
Swap (&lock, &key );
// critical section
}
// remainder section
Operating System Concepts – 7th Edition, Feb 8, 2005 6.15 Silberschatz, Galvin and Gagne ©2005
Semaphore as General Synchronization Tool
Operating System Concepts – 7th Edition, Feb 8, 2005 6.16 Silberschatz, Galvin and Gagne ©2005
Deadlock and Starvation
Deadlock – two or more processes are waiting indefinitely for an
event that can be caused by only one of the waiting processes
Let S and Q be two semaphores initialized to 1
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. .
. .
. .
signal (S); signal (Q);
signal (Q); signal (S);
Starvation – indefinite blocking. A process may never be removed
from the semaphore queue in which it is suspended.
Operating System Concepts – 7th Edition, Feb 8, 2005 6.17 Silberschatz, Galvin and Gagne ©2005
Classical Problems of Synchronization
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
Operating System Concepts – 7th Edition, Feb 8, 2005 6.18 Silberschatz, Galvin and Gagne ©2005
Bounded-Buffer Problem
Operating System Concepts – 7th Edition, Feb 8, 2005 6.19 Silberschatz, Galvin and Gagne ©2005
Bounded Buffer Problem (Cont.)
The structure of the producer process
while (true) {
// produce an item
wait (empty);
wait (mutex);
signal (mutex);
signal (full);
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.20 Silberschatz, Galvin and Gagne ©2005
Bounded Buffer Problem (Cont.)
The structure of the consumer process
while (true) {
wait (full);
wait (mutex);
signal (mutex);
signal (empty);
Operating System Concepts – 7th Edition, Feb 8, 2005 6.21 Silberschatz, Galvin and Gagne ©2005
Readers-Writers Problem
A data set is shared among a number of concurrent processes
Readers – only read the data set; they do not perform any
updates
Writers – can both read and write.
Shared Data
Data set
Semaphore mutex initialized to 1. (Reader)
Semaphore wrt initialized to 1. (writer)
Integer readcount initialized to 0.
Operating System Concepts – 7th Edition, Feb 8, 2005 6.22 Silberschatz, Galvin and Gagne ©2005
Constraints
Data
R2 Set
( R1)
Allow the reader
Data
W1 Set Writer not allowed
( R1)
Data
W2 , R1 Set
( w1)
R1 & W2 not allowed
Operating System Concepts – 7th Edition, Feb 8, 2005 6.23 Silberschatz, Galvin and Gagne ©2005
Readers-Writers Problem
Shared DataData set
Operating System Concepts – 7th Edition, Feb 8, 2005 6.24 Silberschatz, Galvin and Gagne ©2005
Readers-Writers Problem (Cont.)
The structure of a writer process
while (true) {
wait (wrt) ;
// writing is performed
signal (wrt) ;
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.25 Silberschatz, Galvin and Gagne ©2005
Readers-Writers Problem (Cont.)
The structure of a reader process
while (true) {
wait (mutex) ;
readcount ++ ;
if (readcount == 1) wait (wrt) ;
signal (mutex)
// reading is performed
wait (mutex) ;
readcount - - ;
if (readcount == 0) signal (wrt) ;
signal (mutex) ;
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.26 Silberschatz, Galvin and Gagne ©2005
Problems
Operating System Concepts – 7th Edition, Feb 8, 2005 6.27 Silberschatz, Galvin and Gagne ©2005
2. Suppose that the following processes arrive for execution at the
times indicated. Each process will run the listed amount of time. In
answering the questions, use non - preemptive scheduling
Process Arrival Time Burst Time
P1 0.0 8
P2 0.4 4
P3 1.0 1
(i)Calculate the average turnaround time for these processes with
the FCFS scheduling algorithm?
(ii)Calculate the average turnaround time for these processes with
the SJF scheduling algorithm?
(iii)Assume if P1 and P2 waits in the ready queue till 1.0 second will
there be any change in waiting time and Turnaround time?.
Calculate the average turnaround time using FCFS & SJF for
condition (c) & compare both with respect to efficiency.
Operating System Concepts – 7th Edition, Feb 8, 2005 6.28 Silberschatz, Galvin and Gagne ©2005
Solution
s1; wait(s);
signal(s); s2;
signal(s);
Operating System Concepts – 7th Edition, Feb 8, 2005 6.29 Silberschatz, Galvin and Gagne ©2005
Dining-Philosophers Problem
1 3
5 4
Shared data
Bowl of rice (data set)
Semaphore chopstick [5] initialized to 1
Operating System Concepts – 7th Edition, Feb 8, 2005 6.30 Silberschatz, Galvin and Gagne ©2005
Constraints
States: 1. Hungry Eat
2. Eating Both Sticks needed
3. Thinking Sticks are free
(i) When a philosopher is Hungry then
he needs to eat, so he check for the L & R Chop sticks,
if both are available “he can eat”
else “he has to wait until both the sticks are available”
(ii) After eating, both the chopsticks are to be released.
(iii) If the philosopher is thinking then both the chopsticks are
made available.
Operating System Concepts – 7th Edition, Feb 8, 2005 6.31 Silberschatz, Galvin and Gagne ©2005
Dining-Philosophers Problem (Cont.)
The structure of Philosopher i:
While (true) {
// Hungry
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.32 Silberschatz, Galvin and Gagne ©2005
Deadlock and Starvation
Deadlock – two or more processes are waiting indefinitely for an
event that can be caused by only one of the waiting processes
Let S and Q be two semaphores initialized to 1
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. .
. .
. .
signal (S); signal (Q);
signal (Q); signal (S);
Starvation – indefinite blocking. A process may never be removed
from the semaphore queue in which it is suspended.
Operating System Concepts – 7th Edition, Feb 8, 2005 6.33 Silberschatz, Galvin and Gagne ©2005
Problems with Semaphores
Correct use of semaphore operations:
Operating System Concepts – 7th Edition, Feb 8, 2005 6.34 Silberschatz, Galvin and Gagne ©2005
Monitors
A high-level abstraction that provides a convenient and effective
mechanism for process synchronization
Only one process may be active within the monitor at a time
monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }
…
Operating System Concepts – 7th Edition, Feb 8, 2005 6.35 Silberschatz, Galvin and Gagne ©2005
Schematic view of a Monitor
Operating System Concepts – 7th Edition, Feb 8, 2005 6.36 Silberschatz, Galvin and Gagne ©2005
Condition Variables
condition x, y;
Operating System Concepts – 7th Edition, Feb 8, 2005 6.37 Silberschatz, Galvin and Gagne ©2005
Monitor with Condition Variables
Operating System Concepts – 7th Edition, Feb 8, 2005 6.38 Silberschatz, Galvin and Gagne ©2005
Solution to Dining Philosophers
monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];
Operating System Concepts – 7th Edition, Feb 8, 2005 6.39 Silberschatz, Galvin and Gagne ©2005
Solution to Dining Philosophers (cont)
initialization_code() {
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.40 Silberschatz, Galvin and Gagne ©2005
Solution to Dining Philosophers (cont)
dp.pickup (i)
EAT
dp.putdown (i)
Operating System Concepts – 7th Edition, Feb 8, 2005 6.41 Silberschatz, Galvin and Gagne ©2005
Monitor Implementation Using Semaphores
Variables
semaphore mutex; // (initially = 1)
semaphore next; // (initially = 0)
int next-count = 0;
wait(mutex);
…
body of F;
…
if (next-count > 0)
signal(next)
else
signal(mutex);
Operating System Concepts – 7th Edition, Feb 8, 2005 6.42 Silberschatz, Galvin and Gagne ©2005
Monitor Implementation
For each condition variable x, we have:
x-count++;
if (next-count > 0)
signal(next);
else
signal(mutex);
wait(x-sem);
x-count--;
Operating System Concepts – 7th Edition, Feb 8, 2005 6.43 Silberschatz, Galvin and Gagne ©2005
Monitor Implementation
The operation x.signal can be implemented as:
if (x-count > 0) {
next-count++;
signal(x-sem);
wait(next);
next-count--;
}
Operating System Concepts – 7th Edition, Feb 8, 2005 6.44 Silberschatz, Galvin and Gagne ©2005
Synchronization Examples
Solaris
Windows XP
Linux
Pthreads
Operating System Concepts – 7th Edition, Feb 8, 2005 6.45 Silberschatz, Galvin and Gagne ©2005
Solaris Synchronization
Implements a variety of locks to support multitasking,
multithreading (including real-time threads), and multiprocessing
Uses adaptive mutexes for efficiency when protecting data from
short code segments
Uses condition variables and readers-writers locks when longer
sections of code need access to data
Uses turnstiles to order the list of threads waiting to acquire either
an adaptive mutex or reader-writer lock
Operating System Concepts – 7th Edition, Feb 8, 2005 6.46 Silberschatz, Galvin and Gagne ©2005
Windows XP Synchronization
Uses interrupt masks to protect access to global resources on
uniprocessor systems
Uses spinlocks on multiprocessor systems
Also provides dispatcher objects which may act as either mutexes
and semaphores
Dispatcher objects may also provide events
An event acts much like a condition variable
Operating System Concepts – 7th Edition, Feb 8, 2005 6.47 Silberschatz, Galvin and Gagne ©2005
Linux Synchronization
Linux:
disables interrupts to implement short critical sections
Linux provides:
semaphores
spin locks
Operating System Concepts – 7th Edition, Feb 8, 2005 6.48 Silberschatz, Galvin and Gagne ©2005
Pthreads Synchronization
Operating System Concepts – 7th Edition, Feb 8, 2005 6.49 Silberschatz, Galvin and Gagne ©2005
Atomic Transactions
System Model
Log-based Recovery
Checkpoints
Concurrent Atomic Transactions
Operating System Concepts – 7th Edition, Feb 8, 2005 6.50 Silberschatz, Galvin and Gagne ©2005
System Model
Operating System Concepts – 7th Edition, Feb 8, 2005 6.51 Silberschatz, Galvin and Gagne ©2005
Types of Storage Media
Operating System Concepts – 7th Edition, Feb 8, 2005 6.52 Silberschatz, Galvin and Gagne ©2005
Log-Based Recovery
Record to stable storage information about all modifications by a
transaction
Most common is write-ahead logging
Log on stable storage, each log record describes single
transaction write operation, including
Transaction name
Data item name
Old value
New value
<Ti starts> written to log when transaction Ti starts
<Ti commits> written when Ti commits
Log entry must reach stable storage before operation on data
occurs
Operating System Concepts – 7th Edition, Feb 8, 2005 6.53 Silberschatz, Galvin and Gagne ©2005
Log-Based Recovery Algorithm
Using the log, system can handle any volatile memory errors
Undo(Ti) restores value of all data updated by Ti
Redo(Ti) sets values of all data in transaction Ti to new values
Undo(Ti) and redo(Ti) must be idempotent
Multiple executions must have the same result as one
execution
If system fails, restore state of all updated data via log
If log contains <Ti starts> without <Ti commits>, undo(Ti)
If log contains <Ti starts> and <Ti commits>, redo(Ti)
Operating System Concepts – 7th Edition, Feb 8, 2005 6.54 Silberschatz, Galvin and Gagne ©2005
Checkpoints
Log could become long, and recovery could take long
Checkpoints shorten log and recovery time.
Checkpoint scheme:
1. Output all log records currently in volatile storage to stable
storage
2. Output all modified data from volatile to stable storage
3. Output a log record <checkpoint> to the log on stable storage
Now recovery only includes Ti, such that Ti started executing
before the most recent checkpoint, and all transactions after Ti All
other transactions already on stable storage
Operating System Concepts – 7th Edition, Feb 8, 2005 6.55 Silberschatz, Galvin and Gagne ©2005
Concurrent Transactions
Must be equivalent to serial execution – serializability
Could perform all transactions in critical section
Inefficient, too restrictive
Concurrency-control algorithms provide serializability
Operating System Concepts – 7th Edition, Feb 8, 2005 6.56 Silberschatz, Galvin and Gagne ©2005
Serializability
Consider two data items A and B
Consider Transactions T0 and T1
Execute T0, T1 atomically
Execution sequence called schedule
Atomically executed transaction order called serial schedule
For N transactions, there are N! valid serial schedules
Operating System Concepts – 7th Edition, Feb 8, 2005 6.57 Silberschatz, Galvin and Gagne ©2005
Schedule 1: T0 then T1
Operating System Concepts – 7th Edition, Feb 8, 2005 6.58 Silberschatz, Galvin and Gagne ©2005
Nonserial Schedule
Nonserial schedule allows overlapped execute
Resulting execution not necessarily incorrect
Consider schedule S, operations Oi, Oj
Conflict if access same data item, with at least one write
If Oi, Oj consecutive and operations of different transactions & Oi
and Oj don’t conflict
Then S’ with swapped order Oj Oi equivalent to S
If S can become S’ via swapping nonconflicting operations
S is conflict serializable
Operating System Concepts – 7th Edition, Feb 8, 2005 6.59 Silberschatz, Galvin and Gagne ©2005
Schedule 2: Concurrent Serializable Schedule
Operating System Concepts – 7th Edition, Feb 8, 2005 6.60 Silberschatz, Galvin and Gagne ©2005
Locking Protocol
Operating System Concepts – 7th Edition, Feb 8, 2005 6.61 Silberschatz, Galvin and Gagne ©2005
Two-phase Locking Protocol
Generally ensures conflict serializability
Each transaction issues lock and unlock requests in two phases
Growing – obtaining locks
Shrinking – releasing locks
Does not prevent deadlock
Operating System Concepts – 7th Edition, Feb 8, 2005 6.62 Silberschatz, Galvin and Gagne ©2005
Timestamp-based Protocols
Select order among transactions in advance – timestamp-ordering
Transaction Ti associated with timestamp TS(Ti) before Ti starts
TS(Ti) < TS(Tj) if Ti entered system before Tj
TS can be generated from system clock or as logical counter
incremented at each entry of transaction
Timestamps determine serializability order
If TS(Ti) < TS(Tj), system must ensure produced schedule
equivalent to serial schedule where Ti appears before Tj
Operating System Concepts – 7th Edition, Feb 8, 2005 6.63 Silberschatz, Galvin and Gagne ©2005
Timestamp-based Protocol Implementation
Operating System Concepts – 7th Edition, Feb 8, 2005 6.64 Silberschatz, Galvin and Gagne ©2005
Timestamp-ordering Protocol
Suppose Ti executes write(Q)
If TS(Ti) < R-timestamp(Q), value Q produced by Ti was
needed previously and Ti assumed it would never be produced
Write operation rejected, Ti rolled back
If TS(Ti) < W-tiimestamp(Q), Ti attempting to write obsolete
value of Q
Write operation rejected and Ti rolled back
Otherwise, write executed
Any rolled back transaction Ti is assigned new timestamp and
restarted
Algorithm ensures conflict serializability and freedom from deadlock
Operating System Concepts – 7th Edition, Feb 8, 2005 6.65 Silberschatz, Galvin and Gagne ©2005
Schedule Possible Under Timestamp Protocol
Operating System Concepts – 7th Edition, Feb 8, 2005 6.66 Silberschatz, Galvin and Gagne ©2005
End of Chapter 6