Operating System Concepts
Chapter 5 { Process Synchronization
Based on the 9th Edition of:
Abraham Silberschatz, Peter B. Galvin and Jreg Gagne:. Operating System
Concepts
Department of Information Technology, College of Business, Law & Governance
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Learning Objectives
To present the concept of process synchronization.
To introduce the critical-section problem, whose solutions can
be used to ensure the consistency of shared data
To present both software and hardware solutions of the
critical-section problem
To examine several classical process-synchronization problems
To explore several tools that are used to solve process
synchronization problems
Chapter 5 { Process Synchronization Operating System Concepts 2
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Outline
1 Background
2 The Critical-Section Problem
3 Synchronization Hardware
4 Mutex Locks
5 Semaphores
6 Classical Problems of Synchronization
7 Monitors
8 Synchronization examples
Chapter 5 { Process Synchronization Operating System Concepts 3
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Background
Processes can execute concurrently {may be interrupted at
any time, partially completing execution
Concurrent access to shared data may result in data
inconsistency
Maintaining data consistency requires mechanisms to ensure
the orderly execution of cooperating processes
Illustration of the problem:
Suppose that we wanted to provide a solution to the
consumer-producer problem that fills all the buffers. We can
do so by having an integer counter that keeps track of the
number of full buffers. Initially, counter is set to 0. It is
incremented by the producer after it produces a new buffer
and is decremented by the consumer after it consumes a
buffer.
Chapter 5 { Process Synchronization Operating System Concepts 4
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Background
Producer
while (true) f
/* produce an item in next produced */
while (counter == BUFFER SIZE) ;
/* do nothing */
buffer[in] = next produced;
in = (in + 1) % BUFFER SIZE;
counter++;
g
Chapter 5 { Process Synchronization Operating System Concepts 5
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Background
Consumer
while (true) f
while (counter == 0)
/* do nothing */
next consumed = buffer[out];
out = (out + 1) % BUFFER SIZE;
counter—;
/* consume the item in next consumed */
g
Chapter 5 { Process Synchronization Operating System Concepts 6
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Background
Race Condition
counter++ could be implemented as:
register1 = counter
register1 = register1 + 1
counter = register1
counter— could be implemented as:
register2 = counter
register2 = register2 – 1
counter = register2
Chapter 5 { Process Synchronization Operating System Concepts 7
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Background
Race Condition (Cont.)
Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = counter (i.e., register1 = 5)
S1: producer execute register1 = register1 + 1 (i.e., register1 = 6)
S2: consumer execute register2 = counter (i.e., register2 = 5)
S3: consumer execute register2 = register2 1 (i.e., register2 = 4)
S4: producer execute counter = register1 (i.e., counter = 6)
S5: consumer execute counter = register2 (i.e., counter = 4)
Chapter 5 { Process Synchronization Operating System Concepts 8
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
The Critical-Section Problem
Consider system of n processes fp0; p1; : : : ; pn–1g
Each process has critical section segment of code
Process may be changing common variables, updating table,
writing file, etc
When one process in critical section, no other may be in its
critical section
Critical section problem is to design protocol to solve this
Each process must ask permission to enter critical section in
entry section, may follow critical section with exit section,
then remainder section
Chapter 5 { Process Synchronization Operating System Concepts 9
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
The Critical-Section Problem
General structure of process pi
do f
entry section
critical section
exit section
remainder section
g while(true);
Chapter 5 { Process Synchronization Operating System Concepts 10
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
The Critical-Section Problem
Algorithm for process pi
do f
while (turn == j);
critical section
turn = j;
remainder section
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 11
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Solution to Critical-Section Problem
1 Mutual Exclusion { If process Pi is executing in its critical
section, then no other processes can be executing in their
critical sections
2 Progress { If no process is executing in its critical section and
there exist some processes that wish to enter their critical
section, then the selection of the processes that will enter the
critical section next cannot be postponed indefinitely
3 Bounded Waiting { A bound must exist on the number of
times that other processes are allowed to enter their critical
sections after a process has made a request to enter its critical
section and before that request is granted
Assume that each process executes at a nonzero speed
No assumption concerning relative speed of the n processes
Chapter 5 { Process Synchronization Operating System Concepts 12
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Solution to Critical-Section Problem
Critical-Section Handling in OS
Two approaches depending on if kernel is preemptive or
non-preemptive
1 Preemptive { allows preemption of process when running in
kernel mode
2 Non-preemptive { runs until exits kernel mode, blocks, or
voluntarily yields CPU
Essentially free of race conditions in kernel mode
Chapter 5 { Process Synchronization Operating System Concepts 13
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Solution to Critical-Section Problem
Peterson’s Solution { Two process solution
Assume that the load and store machine-language instructions
are atomic; that is, cannot be interrupted
The two processes share two variables:
int turn;
Boolean flag[2];
The variable turn indicates whose turn it is to enter the
critical section
The flag array is used to indicate if a process is ready to enter
the critical section. flag[i] = true implies that process Pi is
ready!
Chapter 5 { Process Synchronization Operating System Concepts 14
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Solution to Critical-Section Problem
Peterson’s Solution { Two process solution (Cont.)
Algorithm for proces pi
do f
flag[i] = true;
turn = j;
while (flag[j] && turn = = j);
critical section
flag[i] = false;
remainder section
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 15
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Solution to Critical-Section Problem
Peterson’s Solution { Two process solution (Cont.)
Provable that the three critical section requirement are met:
1 Mutual exclusion is preserved
Pi enters critical section only if:
either flag[j] = false or turn = i
2 Progress requirement is satisfied
3 Bounded-waiting requirement is met
Chapter 5 { Process Synchronization Operating System Concepts 16
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A race condition .
A. results when several threads try to access the same data
concurrently
B. results when several threads try to access and modify the same
data concurrently
C. will result only if the outcome of execution does not depend on
the order in which instructions are executed
D. None of the above
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 17
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A race condition .
A. results when several threads try to access the same data
concurrently
B. results when several threads try to access and modify the same
data concurrently
C. will result only if the outcome of execution does not depend on
the order in which instructions are executed
D. None of the above
Answer: B
Chapter 5 { Process Synchronization Operating System Concepts 17
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A race condition .
A. results when several threads try to access the same data
concurrently
B. results when several threads try to access and modify the same
data concurrently
C. will result only if the outcome of execution does not depend on
the order in which instructions are executed
D. None of the above
Answer: B
2 An instruction that executes atomically .
A. must consist of only one machine instruction
B. executes as a single, uninterruptible unit
C. cannot be used to solve the critical section problem
D. All of the above
answer:
Chapter 5 { Process Synchronization Operating System Concepts 17
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A race condition .
A. results when several threads try to access the same data
concurrently
B. results when several threads try to access and modify the same
data concurrently
C. will result only if the outcome of execution does not depend on
the order in which instructions are executed
D. None of the above
Answer: B
2 An instruction that executes atomically .
A. must consist of only one machine instruction
B. executes as a single, uninterruptible unit
C. cannot be used to solve the critical section problem
D. All of the above
answer: B
Chapter 5 { Process Synchronization Operating System Concepts 17
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 In Peterson’s solution, the variable indicates if a
process is ready to enter its critical section.
A. turn
B. lock
C. flag[i]
D. turn[i]
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 18
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 In Peterson’s solution, the variable indicates if a
process is ready to enter its critical section.
A. turn
B. lock
C. flag[i]
D. turn[i]
Answer: C
Chapter 5 { Process Synchronization Operating System Concepts 18
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 In Peterson’s solution, the variable indicates if a
process is ready to enter its critical section.
A. turn
B. lock
C. flag[i]
D. turn[i]
Answer: C
2 true or False { A nonpreemptive kernel is safe from race
conditions on kernel data structures.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 18
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 In Peterson’s solution, the variable indicates if a
process is ready to enter its critical section.
A. turn
B. lock
C. flag[i]
D. turn[i]
Answer: C
2 true or False { A nonpreemptive kernel is safe from race
conditions on kernel data structures.
Answer: True
Chapter 5 { Process Synchronization Operating System Concepts 18
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 In Peterson’s solution, the variable indicates if a
process is ready to enter its critical section.
A. turn
B. lock
C. flag[i]
D. turn[i]
Answer: C
2 true or False { A nonpreemptive kernel is safe from race
conditions on kernel data structures.
Answer: True
3 True or False { Race conditions are prevented by requiring
that critical regions be protected by locks.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 18
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 In Peterson’s solution, the variable indicates if a
process is ready to enter its critical section.
A. turn
B. lock
C. flag[i]
D. turn[i]
Answer: C
2 true or False { A nonpreemptive kernel is safe from race
conditions on kernel data structures.
Answer: True
3 True or False { Race conditions are prevented by requiring
that critical regions be protected by locks.
Answer: True
Chapter 5 { Process Synchronization Operating System Concepts 18
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization Hardware
Many systems provide hardware support for implementing the
critical section code.
All solutions below based on idea of locking {protecting
critical regions via locks
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-interruptible)
Either test memory word and set value
Or swap contents of two memory words
Chapter 5 { Process Synchronization Operating System Concepts 19
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization Hardware
Solution to Critical-Section Problem Using Locks
do f
acquire lock
critical section
release lock
remainder section
g while (TRUE);
Chapter 5 { Process Synchronization Operating System Concepts 20
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization Hardware
Test-and-set Instruction
Definition:
boolean test and set (boolean *target)
f
boolean rv = *target;
*target = TRUE;
return rv:
g
Executed atomically
Returns the original value of passed parameter
Set the new value of passed parameter to TRUE.
Chapter 5 { Process Synchronization Operating System Concepts 21
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization Hardware
Solution Using test and set()
Shared Boolean variable lock, initialized to FALSE
Solution:
do f
while (test and set(&lock))
; /* do nothing */
/* critical section */
lock = false;
/* remainder section */
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 22
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization Hardware
Compare and Swap Instruction
Definition:
int compare and swap(int *value, int expected, int new value)
f
int temp = *value;
if (*value == expected)
*value = new value;
return temp;
g
Executed atomically
Returns the original value of passed parameter ’value’
Set the variable ’value’ the value of the passed parameter
’new value’ but only if ’value’ ==’expected’. That is, the
swap takes place only under this condition.
Chapter 5 { Process Synchronization Operating System Concepts 23
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization Hardware
Solution Using compare and swap()
Shared integer ’lock’ initialized to 0;
Solution:
do f
while (compare and swap(&lock, 0, 1) != 0)
; /* do nothing */
/* critical section */
lock = 0;
/* remainder section */
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 24
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Mutex Locks
Previous solutions are complicated and generally inaccessible
to application programmers
OS designers build software tools to solve critical section
problem. Simplest is mutex lock
Protect a critical section by first acquire() a lock then
release() the lock |Boolean variable indicating if lock is
available or not
Calls to acquire() and release() must be atomic |usually
implemented via hardware atomic instructions
But this solution requires busy waiting |this lock therefore
called a spinlock
Chapter 5 { Process Synchronization Operating System Concepts 25
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Mutex Locks
acquire() and release()
acquire() f
while (!available)
; /* busy wait */
available = false;;
g
release() f
available = true;
g
Chapter 5 { Process Synchronization Operating System Concepts 26
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Mutex Locks
Solution Using acquire() and release()
do f
acquire lock
critical section
release lock
remainder section
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 27
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A solution to the critical section problem does not have to
satisfy which of the following requirements?
A. mutual exclusion
B. progress
C. atomicity
D. bounded waiting
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 28
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A solution to the critical section problem does not have to
satisfy which of the following requirements?
A. mutual exclusion
B. progress
C. atomicity
D. bounded waiting
Answer: C
Chapter 5 { Process Synchronization Operating System Concepts 28
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A solution to the critical section problem does not have to
satisfy which of the following requirements?
A. mutual exclusion
B. progress
C. atomicity
D. bounded waiting
Answer: C
2 A mutex lock .
A. is exactly like a counting semaphore
B. is essentially a boolean variable
C. is not guaranteed to be atomic
D. can be used to eliminate busy waiting
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 28
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A solution to the critical section problem does not have to
satisfy which of the following requirements?
A. mutual exclusion
B. progress
C. atomicity
D. bounded waiting
Answer: C
2 A mutex lock .
A. is exactly like a counting semaphore
B. is essentially a boolean variable
C. is not guaranteed to be atomic
D. can be used to eliminate busy waiting
Answer: B
Chapter 5 { Process Synchronization Operating System Concepts 28
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Semaphores
Semaphore S {integer variable{ can only be accessed via two
indivisible (atomic) operations: wait() and signal().
Definition:
wait(S) f
while (S ≤ 0)
; /* busy wait */
S—;
g
signal(S) f
S++;
g
Chapter 5 { Process Synchronization Operating System Concepts 29
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Semaphores
Counting semaphore { integer value can range over an
unrestricted domain
Binary semaphore { integer value can range only between 0
and 1 {same as a mutex lock
Can solve various synchronization problems
Consider P1 and P2 that require S1 to happen before S2.
Create a semaphore ’synch’ initialized to 0
P1:
S1;
signal(synch);
P2:
wait(synch);
S2;
Chapter 5 { Process Synchronization Operating System Concepts 30
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Semaphores
Semaphore Implementation
Must guarantee that no two processes can execute the wait()
and signal() on the same semaphore at the same time
Thus, the implementation becomes the critical section
problem where the wait and signal code are placed in the
critical section
Could now have busy waiting in critical section implementation
{little busy waiting if critical section rarely occupied
Note that applications may spend lots of time in critical
sections and therefore this is not a good solution
Chapter 5 { Process Synchronization Operating System Concepts 31
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Semaphores
Semaphore Implementation with no Busy Waiting
With each semaphore there is an associated waiting queue
Each entry in a waiting queue has two data items:
1 value (of type integer)
2 pointer to next record in the list
Two operations:
1 block { place the process invoking the operation on the
appropriate waiting queue
2 wakeup { remove one of processes in the waiting queue and
place it in the ready queue
Chapter 5 { Process Synchronization Operating System Concepts 32
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Semaphores
Semaphore Implementation with no Busy Waiting
typedef structf
int value;
struct process *list;
g semaphore;
Chapter 5 { Process Synchronization Operating System Concepts 33
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Semaphores
Semaphore Implementation with no Busy Waiting
wait(semaphore *S) f
S ! value—;
if (S ! value < 0) f
add this process to S ! list;
block();
g
g
signal(semaphore *S) f
S ! value++;
if (S ! value <= 0) f
remove a process P from S ! list;
wakeup(P);
g
g
Chapter 5 { Process Synchronization Operating System Concepts 34
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
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 wait(S); wait(Q); . . . signal(S); signal(Q); |
P1 wait(Q); wait(S); . . . signal(Q); signal(S); |
Chapter 5 { Process Synchronization Operating System Concepts 35
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Deadlock and Starvation
Starvation { indefinite blocking
A process may never be removed from the semaphore queue in
which it is suspended
Priority Inversion { Scheduling problem when lower-priority
process holds a lock needed by higher-priority process
Solved via priority-inheritance protocol
Chapter 5 { Process Synchronization Operating System Concepts 36
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A counting semaphore .
A. is essentially an integer variable
B. is accessed through only one standard operation
C. can be modified simultaneously by multiple threads
D. cannot be used to control access to a thread’s critical sections
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 37
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A counting semaphore .
A. is essentially an integer variable
B. is accessed through only one standard operation
C. can be modified simultaneously by multiple threads
D. cannot be used to control access to a thread’s critical sections
Answer: A
Chapter 5 { Process Synchronization Operating System Concepts 37
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A counting semaphore .
A. is essentially an integer variable
B. is accessed through only one standard operation
C. can be modified simultaneously by multiple threads
D. cannot be used to control access to a thread’s critical sections
Answer: A
2 A(n) refers to where a process is accessing/updating
shared data.
A. critical section
B. entry section
C. mutex
D. test-and-set
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 37
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 A counting semaphore .
A. is essentially an integer variable
B. is accessed through only one standard operation
C. can be modified simultaneously by multiple threads
D. cannot be used to control access to a thread’s critical sections
Answer: A
2 A(n) refers to where a process is accessing/updating
shared data.
A. critical section
B. entry section
C. mutex
D. test-and-set
Answer: A
Chapter 5 { Process Synchronization Operating System Concepts 37
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Classical problems used to test newly-proposed synchronization
schemes
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
Chapter 5 { Process Synchronization Operating System Concepts 38
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Bounded-Buffer Problem
n buffers, each can hold one item
Semaphore mutex initialized to the value 1
Semaphore full initialized to the value 0
Semaphore empty initialized to the value n
Chapter 5 { Process Synchronization Operating System Concepts 39
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Bounded-Buffer Problem (Cont.)
The structure of the producer process
do f
. . .
/* produce an item in next produced */
. . .
wait(empty);
wait(mutex);
. . .
/* add next produced to the buffer */
. . .
signal(mutex);
signal(full);
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 40
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Bounded-Buffer Problem (Cont.)
The structure of the consumer process
Do f
wait(full);
wait(mutex);
. . .
/* remove an item from buffer to next consumed */
. . .
signal(mutex);
signal(empty);
/* consume the item in next consumed */
. . .
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 41
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
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
Problem { multiple readers; single writer at the same time
Shared Data
Data set
Semaphore rw mutex initialized to 1
Semaphore mutex initialized to 1
Integer read count initialized to 0
Chapter 5 { Process Synchronization Operating System Concepts 42
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Readers-Writers Problem (Cont.)
The structure of a writer process
do f
wait(rw mutex);
. . .
/* writing is performed */
. . .
signal(rw mutex);
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 43
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Readers-Writers Problem (Cont.)
The structure of a reader process
do f
wait(mutex);
read count++;
if (read count == 1)
wait(rw mutex);
signal(mutex);
..
. /* reading is performed */ …
wait(mutex);
read count—;
if (read count == 0)
signal(rw mutex);
signal(mutex);
g while (true);
Chapter 5 { Process Synchronization Operating System Concepts 44
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Readers-Writers Problem Variations
First variation { no reader kept waiting unless writer has
permission to use shared object
Second variation { once writer is ready, it performs the write
ASAP
Both may have starvation leading to even more variations
Problem is solved on some systems by kernel providing
reader-writer locks
Chapter 5 { Process Synchronization Operating System Concepts 45
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 The first readers-writers problem .
A. requires that, once a writer is ready, that writer performs its
write as soon as possible.
B. is not used to test synchronization primitives.
C. requires that no reader will be kept waiting unless a writer has
already obtained permission to use the shared database.
D. requires that no reader will be kept waiting unless a reader has
already obtained permission to use the shared database.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 46
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 The first readers-writers problem .
A. requires that, once a writer is ready, that writer performs its
write as soon as possible.
B. is not used to test synchronization primitives.
C. requires that no reader will be kept waiting unless a writer has
already obtained permission to use the shared database.
D. requires that no reader will be kept waiting unless a reader has
already obtained permission to use the shared database.
Answer: C
Chapter 5 { Process Synchronization Operating System Concepts 46
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 The first readers-writers problem .
A. requires that, once a writer is ready, that writer performs its
write as soon as possible.
B. is not used to test synchronization primitives.
C. requires that no reader will be kept waiting unless a writer has
already obtained permission to use the shared database.
D. requires that no reader will be kept waiting unless a reader has
already obtained permission to use the shared database.
Answer: C
2 True or False { The value of a counting semaphore can
range only between 0 and 1.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 46
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 The first readers-writers problem .
A. requires that, once a writer is ready, that writer performs its
write as soon as possible.
B. is not used to test synchronization primitives.
C. requires that no reader will be kept waiting unless a writer has
already obtained permission to use the shared database.
D. requires that no reader will be kept waiting unless a reader has
already obtained permission to use the shared database.
Answer: C
2 True or False { The value of a counting semaphore can
range only between 0 and 1.
Answer: False
Chapter 5 { Process Synchronization Operating System Concepts 46
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Dining-Philosophers Problem
Philosophers spend their lives alternating thinking and eating
Don’t interact with their neighbors, occasionally try to pick up
2 chopsticks (one at a time) to eat from bowl {need both to
eat, then release both when done
In the case of 5 philosophers
Shared data
Bowl of rice (data set)
Semaphore chopstick [5]
initialized to 1
RICE
Chapter 5 { Process Synchronization Operating System Concepts 47
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Dining-Philosophers Problem
The structure of Philosopher i:
do f
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );
..
. /* eat */ …
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
..
. /* think */ …
g while (TRUE);
What is the problem with this algorithm? Answer:
Chapter 5 { Process Synchronization Operating System Concepts 48
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Dining-Philosophers Problem
The structure of Philosopher i:
do f
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );
..
. /* eat */ …
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
..
. /* think */ …
g while (TRUE);
What is the problem with this algorithm? Answer: deadlock
What is your solution to this problem? Answer:
Chapter 5 { Process Synchronization Operating System Concepts 48
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Dining-Philosophers Problem
The structure of Philosopher i:
do f
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );
..
. /* eat */ …
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
..
. /* think */ …
g while (TRUE);
What is the problem with this algorithm? Answer: deadlock
What is your solution to this problem? Answer: See the next slide
Chapter 5 { Process Synchronization Operating System Concepts 48
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Dining-Philosophers Problem (Cont.)
Deadlock handling
Allow at most 4 philosophers to be sitting simultaneously at
the table.
Allow a philosopher to pick up the forks only if both are
available (picking must be done in a critical section.
Use an asymmetric solution { an odd-numbered philosopher
picks up first the left chopstick and then the right chopstick.
Even-numbered philosopher picks up first the right chopstick
and then the left chopstick.
Chapter 5 { Process Synchronization Operating System Concepts 49
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Classical Problems of Synchronization
Problems with Semaphores
Incorrect use of semaphore operations:
signal (mutex) . . . wait (mutex)
wait (mutex) . . . wait (mutex)
Omitting of wait (mutex) or signal (mutex) (or both)
Deadlock and starvation are possible.
Chapter 5 { Process Synchronization Operating System Concepts 50
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 occurs when a higher-priority process needs to access a
data structure that is currently being accessed by a
lower-priority process.
A. Priority inversion
B. Deadlock
C. A race condition
D. A critical section
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 51
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 occurs when a higher-priority process needs to access a
data structure that is currently being accessed by a
lower-priority process.
A. Priority inversion
B. Deadlock
C. A race condition
D. A critical section
Answer: A
Chapter 5 { Process Synchronization Operating System Concepts 51
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 occurs when a higher-priority process needs to access a
data structure that is currently being accessed by a
lower-priority process.
A. Priority inversion
B. Deadlock
C. A race condition
D. A critical section
Answer: A
2 What is the correct order of operations for protecting a critical
section using mutex locks?
A. release() followed by acquire()
B. acquire() followed by release()
C. wait() followed by signal()
D. signal() followed by wait()
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 51
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 occurs when a higher-priority process needs to access a
data structure that is currently being accessed by a
lower-priority process.
A. Priority inversion
B. Deadlock
C. A race condition
D. A critical section
Answer: A
2 What is the correct order of operations for protecting a critical
section using mutex locks?
A. release() followed by acquire()
B. acquire() followed by release()
C. wait() followed by signal()
D. signal() followed by wait()
Answer: B
Chapter 5 { Process Synchronization Operating System Concepts 51
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 What is the correct order of operations for protecting a critical
section using a binary semaphore?
A. release() followed by acquire()
B. acquire() followed by release()
C. wait() followed by signal()
D. signal() followed by wait()
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 52
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 What is the correct order of operations for protecting a critical
section using a binary semaphore?
A. release() followed by acquire()
B. acquire() followed by release()
C. wait() followed by signal()
D. signal() followed by wait()
Answer: C
Chapter 5 { Process Synchronization Operating System Concepts 52
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 What is the correct order of operations for protecting a critical
section using a binary semaphore?
A. release() followed by acquire()
B. acquire() followed by release()
C. wait() followed by signal()
D. signal() followed by wait()
Answer: C
2 How many philosophers may eat simultaneously in the Dining
Philosophers problem with 5 philosophers?
A. 1
B. 2
C. 3
D. 5
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 52
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 What is the correct order of operations for protecting a critical
section using a binary semaphore?
A. release() followed by acquire()
B. acquire() followed by release()
C. wait() followed by signal()
D. signal() followed by wait()
Answer: C
2 How many philosophers may eat simultaneously in the Dining
Philosophers problem with 5 philosophers?
A. 1
B. 2
C. 3
D. 5
Answer: B
Chapter 5 { Process Synchronization Operating System Concepts 52
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
A high-level abstraction that provides a convenient and
effective mechanism for process synchronization
Abstract data type, internal variables only accessible by code
within the procedure
monitor monitor-name
f
/* shared variable declarations */
procedure P1 ( . . . ) f . . . g
…
procedure Pn ( . . . ) f . . . g
Initialization code (. . . ) f . . . g
g
Chapter 5 { Process Synchronization Operating System Concepts 53
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Semantic view of a Monitor
entry queue
shared data
operations
initialization
code
. . .
Chapter 5 { Process Synchronization Operating System Concepts 54
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Condition variables
condition x, y;
Two operations are allowed on a condition variable:
x.wait() { a process that invokes the operation is suspended
until x.signal()
x.signal() { resumes one of processes (if any) that invoked
x.wait()
if no x.wait() on the variable, then it has no effect on the
variable
Chapter 5 { Process Synchronization Operating System Concepts 55
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Monitor with condition variables
operations
queues associated with
x, y conditions
entry queue
shared data
x
y
initialization
code
• • •
Chapter 5 { Process Synchronization Operating System Concepts 56
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Condition variables Choices
If process P invokes x.signal(), and process Q is suspended in
x.wait(), what should happen next?
Both Q and P cannot execute in parallel. If Q is resumed,
then P must wait
Options include
Signal and wait { P waits until Q either leaves the monitor or
it waits for another condition
Signal and continue { Q waits until P either leaves the
monitor or it waits for another condition
Both have pros and cons language implementer can decide
Chapter 5 { Process Synchronization Operating System Concepts 57
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Monitor Solution to Dining Philosophers
monitor DiningPhilosophers f
enum f THINKING; HUNGRY, EATING g state [5] ;
condition self [5];
void pickup (int i) f
state[i] = HUNGRY;
test(i);
if (state[i] != EATING) self[i].wait;
g
void putdown (int i) f
state[i] = THINKING;
/* test left and right neighbors */
test((i + 4) % 5);
test((i + 1) % 5);
g
Chapter 5 { Process Synchronization Operating System Concepts 58
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Monitor Solution to Dining Philosophers (Cont.)
void test (int i) f
if ((state[(i + 4) % 5] != EATING) &&
(state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING) ) f
state[i] = EATING ;
self[i].signal () ;
g
g
initialization code() f
for (int i = 0; i < 5; i++)
state[i] = THINKING;
g
g
Chapter 5 { Process Synchronization Operating System Concepts 59
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Monitors
Monitor Solution to Dining Philosophers (Cont.)
Each philosopher i invokes the operations pickup() and
putdown() in the following sequence:
DiningPhilosophers.pickup(i);
EAT
DiningPhilosophers.putdown(i);
No deadlock, but starvation is possible
Chapter 5 { Process Synchronization Operating System Concepts 60
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization in Solaris
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
Uses 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. Turnstiles are
per-lock-holding-thread, not per-object
Chapter 5 { Process Synchronization Operating System Concepts 61
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization in Windows
Uses interrupt masks to protect access to global resources on
uniprocessor systems
Uses spinlocks on multiprocessor systems. Spinlocking-thread
will never be preempted
Also provides dispatcher objects user-land which may act
mutexes, semaphores, events, and timers
An event acts much like a condition variable
Timers notify one or more thread when time expired
Dispatcher objects either signaled-state (object available) or
non-signaled state (thread will block)
Chapter 5 { Process Synchronization Operating System Concepts 62
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Synchronization in Linux
Prior to kernel Version 2.6, disables interrupts to implement
short critical sections
Version 2.6 and later, fully preemptive
Linux provides:
Semaphores
atomic integers
spinlocks
reader-writer versions of both
On single-cpu system, spinlocks replaced by enabling and
disabling kernel preemption
Chapter 5 { Process Synchronization Operating System Concepts 63
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 Which of the following statements is true?
A. Operations on atomic integers do not require locking.
B. Operations on atomic integers do require additional locking.
C. Linux only provides the atomic inc() and atomic sub()
operations.
D. Operations on atomic integers can be interrupted.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 64
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 Which of the following statements is true?
A. Operations on atomic integers do not require locking.
B. Operations on atomic integers do require additional locking.
C. Linux only provides the atomic inc() and atomic sub()
operations.
D. Operations on atomic integers can be interrupted.
Answer: A
Chapter 5 { Process Synchronization Operating System Concepts 64
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 Which of the following statements is true?
A. Operations on atomic integers do not require locking.
B. Operations on atomic integers do require additional locking.
C. Linux only provides the atomic inc() and atomic sub()
operations.
D. Operations on atomic integers can be interrupted.
Answer: A
2 True or False { The local variables of a monitor can be
accessed by only the local procedures.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 64
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 Which of the following statements is true?
A. Operations on atomic integers do not require locking.
B. Operations on atomic integers do require additional locking.
C. Linux only provides the atomic inc() and atomic sub()
operations.
D. Operations on atomic integers can be interrupted.
Answer: A
2 True or False { The local variables of a monitor can be
accessed by only the local procedures.
Answer: True
Chapter 5 { Process Synchronization Operating System Concepts 64
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 Which of the following statements is true?
A. Operations on atomic integers do not require locking.
B. Operations on atomic integers do require additional locking.
C. Linux only provides the atomic inc() and atomic sub()
operations.
D. Operations on atomic integers can be interrupted.
Answer: A
2 True or False { The local variables of a monitor can be
accessed by only the local procedures.
Answer: True
3 True or False { Monitors are a theoretical concept and are
not practiced in modern programming languages.
Answer:
Chapter 5 { Process Synchronization Operating System Concepts 64
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
Quick Quiz
1 Which of the following statements is true?
A. Operations on atomic integers do not require locking.
B. Operations on atomic integers do require additional locking.
C. Linux only provides the atomic inc() and atomic sub()
operations.
D. Operations on atomic integers can be interrupted.
Answer: A
2 True or False { The local variables of a monitor can be
accessed by only the local procedures.
Answer: True
3 True or False { Monitors are a theoretical concept and are
not practiced in modern programming languages.
Answer: False
Chapter 5 { Process Synchronization Operating System Concepts 64
Background Critical-Section Synchronization Mutex Semaphores Classical Problems Monitors Examples
End of Chapter 5
Chapter 5 { Process Synchronization Operating System Concepts 65