Operating Systems
Phan Xuan Hieu
Data Science & Knowledge Technology Lab
Faculty of IT, VNU-UET
hieupx@[Link]
Process Synchronization
Objectives
§ Describe the critical-section problem and illustate a race
condition
§ Demonstrate how mutex locks, semaphores, monitors, and
condition variables can be used to solve the critical section
problem
§ Evaluate tools that solve the critical-section problem in
low-, moderate-, and high-contention scenarios
§ Explain the bounded-buffer, readers-writers, and dining
philosopher synchronization problems.
3
Materials
§ Textbook:
• A. Silberschatz, P. B. Galvin, and G. Gagne: Operating System Concepts,
10th edition, John Wiley & Sons, 2018.
• Chapter 6 and 7
§ Futher reading:
• W. Stallings: Operating Systems: Internals and Design Principles, 9th
edition, Pearson Education Limited, 2018.
• Chapter 5
• A. S. Tanenbaum and H. Bos: Modern Operating Systems, 4th edition,
Pearson Prentice Hall, 2015.
• Chapter 2
4
Contents
§ Part 1: Synchronization tools
§ Part 2: Synchronization examples
5
Contents
§ Part 1: Synchronization tools
§ Part 2: Synchronization examples
6
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
7
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
8
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 producer-
consumer problem that fills all the buffer. We can do so by having an
integer counter that keeps track of the number of buffer items.
Initially, counter is set to 0. It is incremented by the producer
after it produces an item and is decremented by the consumer after
it consumes an item from the buffer.
9
Producer
10
Consumer
11
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
§ Consider if execution interleaving with “counter = 5” initially:
• S0: producer executes register1 = counter (register1 = 5)
• S1: producer executes register1 = register1 + 1 (register1 = 6)
• S2: consumer executes register2 = counter (register2 = 5)
• S3: consumer executes register2 = register2 – 1 (register2 = 4)
• S4: producer executes counter = register1 (counter = 6)
• S5: consumer executes counter = register2 (counter = 4)
12
Race condition (cont.)
§ Process P0 and P1 are creating child processes using the fork()
system call
§ Race condition on kernel variable next_available_pid which
represents the next available process identifier (pid)
§ Unless there is mutual exclusion, the same pid could be assigned to
two different processes!
13
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
14
The 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 its critical
section in entry section, may follow critical section with
exit section, then remainder section
15
General structure of critical section
16
Solution to critical-section problem
§ Mutual exclusion: if process Pi is executing in its critical
section, then no other processes can be executing in their
critical sections
§ Progress: if no process is executing in its critical section and
there exist some processes that wish to enter their critical
section, then only those processes that are not executing in
their remainder sections can participate in deciding which will
enter its critical section next, and this selection cannot be
postponed indefinitely
§ 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 non-zero speed
• No assumption concerning relative speed of the n processes
17
Critical-section handling in OS
§ Two approaches depending on if kernel is preemptive or
non-preemptive
• Preemptive: allows preemption of process when running in kernel
mode
• Non-preemptive: runs until exits kernel mode, blocks, or
voluntarily yields CPU
• Essentially free of race conditions in kernel mode
18
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
19
Peterson’s solution
§ Not guaranteed to work on modern architectures! (But 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.
20
Algorithm for process Pi
while (true){
flag[i] = true;
turn = j;
while (flag[j] && turn == j);
/* critical section */
flag[i] = false;
/* remainder section */
}
21
Peterson’s solution (cont.)
Provable that the three CS requirement are met:
1. Mutual exclusion is preserved
Pi enter CS only if:
either flag[j] = false or turn = i
2. Progress requirement is satisfied
3. Bounded-waiting requirement is met
22
Peterson’s solution (cont.)
§ Although useful for demonstrating an algorithm, Peterson’s
solution is not guaranteed to work on modern
architectures.
§ Understanding why it will not work is also useful for better
understanding race conditions.
§ To improve performance, processors and/or compliers
may reorder operations that have no dependencies.
§ For single-threaded this is ok as the result will always be
the same.
§ For multithreaded the reordering may produce
inconsistent or unexpected results!
23
Peterson’s solution (cont.)
§ Two threads share the data:
boolean flag = false;
int x = 0;
§ Thread 1 performs:
while (!flag);
printf(x);
§ Thread 2 performs:
x = 100;
flag = true;
§ What is the expected output?
24
Peterson’s solution (cont.)
§ 100 is the expected output.
§ However, the operations for Thread 2 may be reordered:
flag = true;
x = 100;
§ If this occurs, the output may be 0!
§ The effects of instruction reordering in Peterson’s solution
§ This allows both processes to be in their critical section at the same
time!
25
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
26
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 such as compare-
and-swap
§ But this solution requires busy waiting
• This lock therefore called a spinlock
27
Solution to critical-section problem using locks
28
Mutex lock definitions
§ These two functions must be implemented atomically.
§ Both test-and-set and compare-and-swap can be used to
implemented these functions.
29
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
30
Semaphore
§ Synchronization tool that provides more sophisticated
ways (than mutex lock) for process to synchronize their
activities.
§ Semaphore S – an integer variable
§ Can only be accessed via two indivisible (atomic)
operations
• wait() – originally called P() – proberen (check)
• signal() - originally called V() – verhogen (increase)
31
Definition of wait() and signal()
§ Definition of wait()
§ Definition of signal()
32
Semaphore usage
§ Counting semaphore – integer value can range over an
unrestricted domain
§ Binary semaphore – integer value can range only
between 0 and 1. The same as mutex lock.
§ Can solve various synchronization problems
§ Consider processes P1 and P2 that require S1 to happen
before S2. Create a semaphore “synch” initialized to 0.
Process P1: Process P2:
33
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 wait and signal code are placed in the
critical section
• Could now have busy waiting in critical section implementation
• But implementation code is short
• 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
34
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:
• value (of type integer)
• pointer to next record in the list
§ Two operations:
• block – place the process invoking the operation on the appropriate waiting
queue
• wakeup – remove one of processes in the waiting queue and place it in the
ready queue
§ Semaphore structure:
typedef struct {
int value;
struct process * list;
}
35
Implementation with no busy waiting (cont.)
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}
36
Problems with semaphores
§ Incorrect use of semaphore operations:
• signal(S) … wait(S)
• wait(S) … wait(S)
• Omitting of wait(S) and/or signal(S)
§ These – and others – are examples of what can occur
when semaphores and other synchronization tools are
used incorrectly.
37
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
38
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
§ Only one process may be active within the monitor at a time
§ Pseudocode syntax of a monitor:
monitor monitor-name
{
// shared variable declarations
function P1 (…) { …. }
function P2 (…) { …. }
function Pn (…) {……}
initialization code (…) { … }
}
39
Schematic view of a monitor
40
Condition variables
§ condition x, y;
§ Two operations are allowed on a condition variable:
• [Link]() – a process that invokes the operation is suspended
until [Link]()
• [Link]() – resumes one of processes (if any) that invoked
[Link]()
• If no [Link]() on the variable, then it has no effect on the variable
41
Monitor with condition variables
42
Condition variables choices
§ If process P invokes [Link](), and process Q is
suspended in [Link](), 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
• Monitors implemented in Concurrent Pascal compromise
• P executing signal immediately leaves the monitor, Q is resumed
• Implemented in other languages including Mesa, C#, Java
43
Part 1: Synchronization tools
§ Background
§ The critical-section problem
§ Peterson’s solution
§ Mutex locks
§ Semaphores
§ Monitors
§ Liveness
44
Liveness
§ Processes may have to wait indefinitely while trying to
acquire a synchronization tool such as a mutex lock or
semaphore.
§ Waiting indefinitely violates the progress and bounded-
waiting criteria discussed at the beginning of this lecture.
§ Liveness refers to a set of properties that a system must
satisfy to ensure processes make progress.
§ Indefinite waiting is an example of a liveness failure.
45
Liveness (cont.)
§ 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
§ Consider if P0 executes wait(S) and P1 wait(Q). When P0 executes wait(Q),
it must wait until P1 executes signal(Q)
§ However, P1 is waiting until P0 executes signal(S)
§ Since these signal() operations will never be executed, P0 and P1 are
deadlocked.
46
Liveness (cont.)
Other forms of deadlock:
§ 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
§ Solve via priority-inheritance protocol
47
Priority inheritance protocol
§ Consider the scenario with three processes P1, P2, and P3. P1
has the highest priority, P2 the next highest, and P3 the lowest.
Assume P3 is assigned a resource R that P1 wants. Thus, P1
must wait for P3 to finish using the resource. However, P2
becomes runnable and preempts P3. What has happened is that
P2 - a process with a lower priority than P1 - has indirectly
prevented P3 from gaining access to the resource.
§ To prevent this from occurring, a priority inheritance
protocol is used. This simply allows the priority of the highest
thread waiting to access a shared resource to be assigned to
the thread currently using the resource. Thus, the current
owner of the resource is assigned the priority of the highest
priority thread wishing to acquire the resource.
48
Contents
§ Part 1: Synchronization tools
§ Part 2: Synchronization examples
49
Part 2: Synchronization examples
§ Bounded-buffer problem
§ Readers and writers problem
§ Dining philosophers problem
50
Part 2: Synchronization examples
§ Bounded-buffer problem
§ Readers and writers problem
§ Dining philosophers problem
51
Bounded-buffer problem
§ Buffer with size n (i.e., maximum n items)
§ Semaphore mutex initialized to the value 1
§ Semaphore full initialized to the value 0
§ Semaphore empty initialized to the value n
52
The structure of the producer process
while (true) {
...
/* produce an item in next_produced */
...
wait(empty);
wait(mutex);
...
/* add next produced to the buffer */
...
signal(mutex);
signal(full);
}
53
The structure of the consumer process
while (true) {
wait(full);
wait(mutex);
...
/* remove an item from buffer to next_consumed */
...
signal(mutex);
signal(empty);
...
/* consume the item in next consumed */
...
}
54
Part 2: Synchronization examples
§ Bounded-buffer problem
§ Readers and writers problem
§ Dining philosophers problem
55
Readers and 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 properties
§ Shared data
• Data set
• Semaphore rw_mutex initialized to 1
• Semaphore mutex initialized to 1
• Integer read_count initialized to 0
56
The structure of the writer process
57
The structure of the reader process
58
Readers and 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
59
Part 2: Synchronization examples
§ Bounded-buffer problem
§ Readers and writers problem
§ Dining philosophers problem
60
Dining philosopher 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
61
The structure of philosopher i
What is the problem with this algorithm?
62
Monitor solution to dining philosophers
monitor DiningPhilosophers
{
enum {THINKING, HUNGRY, EATING} state [5];
condition self [5];
void pickup (int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING) self[i].wait();
}
void putdown (int i) {
state[i] = THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
63
Monitor solution to dining philosophers (cont.)
void test (int i) {
if ((state[(i + 4) % 5] != EATING) &&
(state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING) ) {
state[i] = EATING;
self[i].signal () ;
}
}
initialization_code() {
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
}
64
Solution to dining philosophers (cont.)
§ Each philosopher I invokes the operations pickup() and
putdown() in the following sequence:
[Link](i);
/** EAT **/
[Link](i);
§ No deadlock, but starvation is possible
65
Summary
§ Concurrent
§ Critical section
§ Synchronization solutions:
• Peterson’s solution
• Mutex lock
• Semaphores
• Monitors
§ Synchronization examples
• Bounded-buffer problem
• Readers and writers problem
• Dining philosophers problem
66