Chapter 6:
PROCESS SYNCHRONIZATION
Chapter 6: Process Synchronization
Background
The Critical-Section Problem
Peterson’s Solution
Synchronization Hardware
Mutex Locks
Semaphores
Classic Problems of Synchronization
Monitors
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.
Producer Consumer Problem
Race Condition
Producer
while (true) {
/* produce an item in next produced */
while (counter == BUFFER_SIZE) ;
/* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}
Consumer
while (true) {
while (counter == 0)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in next consumed */
}
Critical Section Problem
Consider system of n processes {p0, p1, … pn-1}
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
Critical Section
General structure of process Pi
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
Algorithm for Process Pi
do {
while (turn == j);
critical section
turn = j;
remainder section
} while (true);
Peterson’s Solution
Good algorithmic description of solving the problem
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!
Algorithm for Process Pi
do {
flag[i] = true;
turn = j;
while (flag[j] && turn = = j);
critical section
flag[i] = false;
remainder section
} while (true);
Peterson’s Solution (Cont.)
Provable that the three CS requirement are met:
1. Mutual exclusion is preserved
Pi enters CS only if:
either flag[j] = false or turn = i
2. Progress requirement is satisfied
3. Bounded-waiting requirement is met
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
Solution to Critical-section Problem Using Locks
do {
acquire lock
critical section
release lock
remainder section
} while (TRUE);
test_and_set() Instruction
Test-and-set does two things atomically:
Test a lock (whose value is returned)
Set the lock
Lock obtained when the return value is FALSE
If TRUE, someone already had the lock (and
still has it)
test_and_set() Instruction
Shared Boolean variable lock, initialized to FALSE
Definition:
boolean test_and_set (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}
___________________________________________________________
Mutual-exclusion Implementation:
do{
while (test_and_set(&lock))
; /* do nothing */
/* critical section */
lock = false;
/* remainder section */
} while (true);
test_and_set() Instruction
FALSE
test_and_set() Instruction
test_and_set() Instruction
test_and_set() Instruction
test_and_set() Instruction
test_and_set() Instruction
test_and_set() Instruction
compare_and_swap Instruction
Definition:
int compare _and_swap(int *value, int expected, int
new_value) {
int temp = *value;
if (*value == expected)
*value = new_value;
return temp;
}
1. Executed atomically
2. Returns the original value of passed parameter “value”
3. 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.
Solution using compare_and_swap
Shared integer “lock” initialized to 0;
Solution:
do {
while (compare_and_swap(&lock, 0, 1) != 0)
; /* do nothing */
/* critical section */
lock = 0;
/* remainder section */
} while (true);
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( short for mutual exclusion)
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
acquire() and release()
acquire() {
while (!available)
; /* busy wait */
available = false;
}
release() {
available = true;
}
do {
acquire lock
critical section
release lock
remainder section
} while (true);
Semaphore
Synchronization tool that provides more sophisticated ways (than Mutex
locks) for process to synchronize their activities.
Semaphore S – integer variable
Can only be accessed via two indivisible (atomic) operations
wait() and signal()
Originally called P() and V()
[P stands for Proberen meaning “to test”
V stands for Verhogen meaning “to increment”]
Definition of the wait() operation
wait(S) {
while (S <= 0)
; // busy wait
S--;
}
Definition of the signal() operation
signal(S) {
S++;
}
Semaphore Usage
Counting semaphore – integer value can range over an
unrestricted domain
Used to control access to a given resource consisting of a finite number
of resources. The semaphore is initialized to the number of resources.
Binary semaphore – integer value can range only between 0 and 1
Same as a mutex lock
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 ;
Can implement a counting semaphore S as a binary semaphore
Semaphore Implementation with no Busy waiting
The definition of wait() and signal() operation can suffer from busy
waiting.
Two operations:
block – place the process invoking the operation on the waiting
queue associated with the semaphore
wakeup – remove one of processes in the waiting queue and
place it in the ready queue
Definition of Semaphore:
typedef struct{
int value;
struct process *list;
} semaphore;
Semaphore Implementation with no Busy waiting
Each semaphore has an integer value and a processes list. When a
process must wait on a semaphore, it is added to the list of processes.
A signal() operation removes one process from the list of waiting
processes and awakens that process.
Semaphore Implementation with no Busy waiting (Cont.)
wait(semaphore S) {
S->value--;
if (S->value < 0) {
add this process to waiting list (S->list);
block();
}
}
After decreasing the counter by 1, if the counter value becomes negative, then
add the caller to the waiting list, and then
block itself.
signal(semaphore S) {
S->value++;
if (S->value <= 0) {
remove a process P from waiting list (S->list);
wakeup(P);
}
}
After increasing the counter by 1, if the new counter value is not positive, then
remove a process P from the waiting list,
resume the execution of process P, and return
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
Priority Inversion – Scheduling problem when lower-priority
process holds a lock needed by higher-priority process
Solved via priority-inheritance protocol
Classical Problems of Synchronization
Classical problems used to test newly-proposed synchronization
schemes
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
Bounded-Buffer Problem
Suppose we have a circular buffer of n slots.
Pointers in and out points to the first empty and filled slot respectively.
Producer processes keep adding info into the buffer
Consumer processes keep retrieving info from the buffer.
Bounded-Buffer Problem
A producer deposits info into Buf[in] and a consumer retrieves info
from Buf[out].
in and out must be advanced.
in is shared among producers.
out is shared among consumers.
If Buf is full, producers should be blocked.
If Buf is empty, consumers should be blocked.
Bounded-Buffer Problem
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 –
Allow multiple readers to read at the same time
Only one single writer can access the shared data at the same time
Several variations of how readers and writers are considered – all
involve some form of priorities
First reader-writer problem: No reader will be kept waiting
Second reader-writer problem: No writer is kept waiting
Both may result in Starvation
Solution to First Reader-Writer Problem:
Shared Data:
Semaphore rw_mutex initialized to 1(Common to both reader and writer)
Semaphore mutex initialized to 1(Used to ensure mutual exclusion when
variable read_count is updated)
Integer read_count initialized to 0 (Keeps track of how many processes are
currently reading the object)
Readers-Writers Problem (Cont.)
The structure of a writer process
do {
wait(rw_mutex);
...
/* writing is performed */
...
signal(rw_mutex);
} while (true);
Semaphore rw_mutex functions as a mutual exclusion semaphore for the
writer. It is also used by first or last reader that enters or exits the critical
section. It is not used by readers who enter or exit while other readers are in
their critical section.
Readers-Writers Problem (Cont.)
The structure of a reader process
do {
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);
} while (true);
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
Dining-Philosophers Problem
It is a simple representation of the need to allocate several resources
among several processes in a deadlock-free and starvation-free manner.
Philosophers spend their lives alternating thinking and eating
Don’t interact with their neighbors, occasionally when a philosopher gets
hungry, he sits down, picks up two nearest chopsticks (one at a time) to
eat from bowl
Need both to eat, then release both when done
Dining-Philosophers Problem Algorithm
Chopsticks are shared items (by two philosophers) and must be protected.
Each chopstick has a semaphore with initial value 1.
A philosopher calls wait() before picks up a chopstick and calls signal() to
release it.
Dining-Philosophers Problem Algorithm (Cont.)
Deadlock
Suppose that all 5 philosophers become hungry at the same time and
each grabs their left chopstick. All the elements of the chopstick are
now 0. When each philosophers tries to grab their right chopstick, they
will be delayed forever.
An easy way to remove this deadlock is to introduce a philosopher who
picks up his right chopstick first!
Dining-Philosophers Problem Algorithm (Cont.)
Another Deadlock handling condition
Allow at most 4 philosophers to be sitting simultaneously at the
table.
End