Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Synchronization Tools

Operating System Concepts – 10h Edition Silberschatz, Galvin and Gagne ©2018
Current Standing

 Lecture Zero for Overview


 Introduction of OS
 Operating-System Services
 Process
 Threads & Concurrency
 CPU Scheduling
• FCFS
• SJF
• RR

 Lab 8/12
 Assignment 2/3
 Quiz 2/5
 OHT 1 /2
 ESE 0/1

Operating System Concepts – 10th Edition 1.2 Silberschatz, Galvin and Gagne ©2018
Outline
 The Critical-Section Problem
 Peterson’s Solution
 Hardware Support for Synchronization
 Mutex Locks
 Semaphores
 Monitors
 Liveness
 Evaluation

Operating System Concepts – 10th Edition 1.3 Silberschatz, Galvin and Gagne ©2018
Objectives
 Describe the critical-section problem and illustrate a race condition

 Illustrate hardware solutions to the critical-section problem using memory


barriers, compare-and-swap operations, and atomic variables

 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

c
Operating System Concepts – 10th Edition 1.4 Silberschatz, Galvin and Gagne ©2018
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

 We illustrated in chapter 4 the problem when we considered the Bounded Buffer


problem with use of a counter that is updated concurrently by the producer and
consumer,. Which lead to race condition.

Operating System Concepts – 10th Edition 1.5 Silberschatz, Galvin and Gagne ©2018
Race Condition
 Processes 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 a mechanism to prevent P0 and P1 from accessing the variable


next_available_pid the same pid could be assigned to two different processes!

Operating System Concepts – 10th Edition 1.6 Silberschatz, Galvin and Gagne ©2018
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

Operating System Concepts – 10th Edition 1.7 Silberschatz, Galvin and Gagne ©2018
Critical Section

 General structure of process Pi

Operating System Concepts – 10th Edition 1.8 Silberschatz, Galvin and Gagne ©2018
Critical-Section Problem (Cont.)
Requirements for 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 some processes


wish to enter their critical sections, then only those processes that are not
executing in their remainder sections can participate in deciding which will enter
its critical section next..

3. Bounded Waiting - A bound/limit 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

Operating System Concepts – 10th Edition 1.9 Silberschatz, Galvin and Gagne ©2018
Interrupt-based Solution
 Entry section: disable interrupts
 Exit section: enable interrupts
 Will this solve the problem?
• What if the critical section is code that runs for an hour?
• Can some processes starve – never enter their critical section.
• What if there are two CPUs?

Operating System Concepts – 10th Edition 1.10 Silberschatz, Galvin and Gagne ©2018
Software Solution 1

 Two process solution


 Assume that the load and store machine-language instructions are atomic;
that is, cannot be interrupted

 The two processes share one variable:


• int turn;

 The variable turn indicates whose turn it is to enter the critical section

 initially, the value of turn is set to i

Operating System Concepts – 10th Edition 1.11 Silberschatz, Galvin and Gagne ©2018
Algorithm for Process Pi

while (true){

while (turn = = j);

/* critical section */

turn = i;

/* remainder section */

Operating System Concepts – 10th Edition 1.12 Silberschatz, Galvin and Gagne ©2018
Correctness of the Software Solution

 Mutual exclusion is preserved


Pi enters critical section only if:
turn = j
and turn cannot be both 0 and 1 at the same time

 What about the Progress requirement?


 What about the Bounded-waiting requirement?

Operating System Concepts – 10th Edition 1.13 Silberschatz, Galvin and Gagne ©2018
Modern Architecture Example

 Two threads share the data:


boolean flag = false;
int x = 0;
 Thread 1 performs
while (!flag)
;
print x
 Thread 2 performs
x = 100;
flag = true
 What is the expected output?

100

Operating System Concepts – 10th Edition 1.19 Silberschatz, Galvin and Gagne ©2018
Modern Architecture Example (Cont.)

 However, since the variables flag and x are independent of each


other, the instructions:

flag = true;
x = 100;

for Thread 2 may be reordered


 If this occurs, the output may be 0!

Operating System Concepts – 10th Edition 1.20 Silberschatz, Galvin and Gagne ©2018
Hardware Support for Synchronization

 Software-based solutions are not guaranteed to work on modern computer


architectures.
• because the algorithm involves no special support from the operating system or
specific hardware instructions to ensure mutual exclusion
 We present three hardware instructions that provide support for solving the critical-
section problem.

 Memory barrier
 Hardware instruction
 Atomic Variables

Operating System Concepts – 10th Edition 1.22 Silberschatz, Galvin and Gagne ©2018
Memory Barrier
 We saw that a system may reorder instructions, a policy that can lead to unreliable
data states.
 Memory model are the memory guarantees a computer architecture makes to
application programs.
 Memory models may be either:
• Strongly ordered – where a memory modification of one processor is
immediately visible to all other processors.

• Weakly ordered – where a memory modification of one processor may not be


immediately visible to all other processors.

 Memory models vary by processor type, so kernel developers cannot make any
assumptions regarding the visibility of modifications to memory on a shared-memory
multiprocessor;
 A memory barrier is an instruction that forces any change in memory to be
propagated (made visible) to all other processors.

Operating System Concepts – 10th Edition 1.23 Silberschatz, Galvin and Gagne ©2018
Memory Barrier Instructions

 When a memory barrier instruction is performed, the system ensures that all loads
and stores are completed before any subsequent load or store operations are
performed.

 Therefore, even if instructions were reordered, the memory barrier ensures that
the store operations are completed in memory and visible to other processors
before future load or store operations are performed.

Operating System Concepts – 10th Edition 1.24 Silberschatz, Galvin and Gagne ©2018
Memory Barrier Example
 Returning to the example
 We could add a memory barrier to the following instructions to ensure Thread 1
outputs 100:
 Thread 1 now performs
while (!flag)
memory_barrier();
print x
 Thread 2 now performs
x = 100;
memory_barrier();
flag = true
 For Thread 1 we are guaranteed that that the value of flag is loaded before the
value of x.
 For Thread 2 we ensure that the assignment to x occurs before the assignment
flag.

Operating System Concepts – 10th Edition 1.25 Silberschatz, Galvin and Gagne ©2018
Terms
Busy waiting means a process simply spins, (does nothing but continue to
test its entry condition) while it is waiting to enter its critical section. This
continues to use (waste) CPU cycles, which is inefficient

Operating System Concepts – 10th Edition 1.35 Silberschatz, Galvin and Gagne ©2018
Mutex Locks
 OS designers build software tools to solve critical section problem
 Simplest is mutex lock
• Boolean variable indicating if lock is available or not
 Protect a critical section by
• First acquire() a lock
• Then release() the lock
 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
 spinlock keeps checking the lock (busy waiting), while mutex puts threads
waiting for the lock into sleep (blocked).

Atomic: No one can modify the memory location at the same memory
scope during the atomic sequence
Operating System Concepts – 10th Edition 1.36 Silberschatz, Galvin and Gagne ©2018
Solution to CS Problem Using Mutex Locks

while (true) {
acquire lock

critical section

release lock

remainder section
}

Operating System Concepts – 10th Edition 1.37 Silberschatz, Galvin and Gagne ©2018
Solution to CS Problem Using Mutex Locks

Operating System Concepts – 10th Edition 1.38 Silberschatz, Galvin and Gagne ©2018
Multithreaded C Program (Cont.)
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void initialize(int array[]){


for(int i=0;i<100;i++){
array[i] = i;
}
}
void *sum_function(void *ptr);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int sum = 0;
int array[100];
int count = 0;
 

Operating System Concepts – 10th Edition 1.39 Silberschatz, Galvin and Gagne ©2018
Multithreaded C Program (Cont.)
void main(){
initialize(array);
pthread_t thread_id[4];

for (int i=0;i<4;i++){


pthread_create(&thread_id[i],NULL,sum_function,NULL); }
for (int i=0;i<4;i++){
pthread_join(thread_id[i],NULL);
}
printf("Value of sum is : %d\n",sum);
exit(EXIT_SUCCESS);
}

Operating System Concepts – 10th Edition 1.40 Silberschatz, Galvin and Gagne ©2018
Multithreaded C Program (Cont.)

void *sum_function(void *ptr)


{
pthread_mutex_lock( &mutex1);
int x = count+25;
while(count < x){
sum+=array[count];
count++;
}
pthread_mutex_unlock( &mutex1);
}

Operating System Concepts – 10th Edition 1.41 Silberschatz, Galvin and Gagne ©2018
Semaphore

 A semaphore is a signaling mechanism and a thread that is waiting on a semaphore can


be signaled by another thread. This is different than a mutex as the mutex can be
signaled only by the thread that called the wait function.

 A semaphore uses two atomic operations, wait and signal for process synchronization.

 The wait operation decrements the value of its argument S, if it is positive. If S is


negative or zero, then no operation is performed.

 There are mainly two types of semaphores i.e. counting semaphores and binary
semaphores.

 Counting Semaphores are integer value semaphores and have an unrestricted value
domain. These semaphores are used to coordinate the resource access, where the
semaphore count is the number of available resources.

Operating System Concepts – 10th Edition 1.42 Silberschatz, Galvin and Gagne ©2018
Semaphore

 Synchronization tool that provides more sophisticated ways (than Mutex locks) for processes 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()
 Definition of the wait() operation
wait(S) {
while (S <= 0)
; // busy wait
S--;
}
 Definition of the signal() operation
signal(S) {
S++;
}

Operating System Concepts – 10th Edition 1.43 Silberschatz, Galvin and Gagne ©2018
Semaphore (Cont.)
 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 implement a counting semaphore S as a binary semaphore
 With semaphores we can solve various synchronization problems

Operating System Concepts – 10th Edition 1.44 Silberschatz, Galvin and Gagne ©2018
Semaphore Usage Example
 Solution to the CS Problem
• Create a semaphore “S” initialized to 1
wait(S);
CS
signal(S);
 Consider P1 and P2 that with two statements S1 and S2 and the requirement that S1 to
happen before S2
• Create a semaphore “S” initialized to 0
P1:
Statement1;
signal(S);
P2:
wait(S);
Statement2;

Operating System Concepts – 10th Edition 1.45 Silberschatz, Galvin and Gagne ©2018
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
• 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

Operating System Concepts – 10th Edition 1.46 Silberschatz, Galvin and Gagne ©2018
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

Operating System Concepts – 10th Edition 1.47 Silberschatz, Galvin and Gagne ©2018
Problems with Semaphores

 Incorrect use of semaphore operations:

• signal(mutex) …. wait(mutex)

• wait(mutex) … wait(mutex)

• Omitting of wait (mutex) and/or signal (mutex)

 These – and others – are examples of what can occur when


semaphores and other synchronization tools are used incorrectly.

Operating System Concepts – 10th Edition 1.50 Silberschatz, Galvin and Gagne ©2018
Activity

Operating System Concepts – 10th Edition 1.69 Silberschatz, Galvin and Gagne ©2018
Activity

Operating System Concepts – 10th Edition 1.70 Silberschatz, Galvin and Gagne ©2018
Activity

Operating System Concepts – 10th Edition 1.71 Silberschatz, Galvin and Gagne ©2018
Dining Philosophers Problem
 The dining philosophers problem states that there are 5 philosophers sharing a circular table
and they eat and think alternatively. There is a bowl of rice for each of the philosophers and
5 chopsticks. A philosopher needs both their right and left chopstick to eat. A hungry
philosopher may only eat if there are both chopsticks available. Otherwise a philosopher
puts down their chopstick and begin thinking again.
 The dining philosopher is a classic synchronization problem as it demonstrates a large class
of concurrency control problems.

Operating System Concepts – 10th Edition 1.72 Silberschatz, Galvin and Gagne ©2018
Dining Philosophers Problem
 semaphore chopstick [5]; In the structure, first wait operation is performed on
 do { chopstick[i] and chopstick[ (i+1) % 5]. This means
 wait( chopstick[i] );
that the philosopher i has picked up the chopsticks
on his sides. Then the eating function is performed.
 wait( chopstick[ (i+1) % 5] );
After that, signal operation is performed on
 .. chopstick[i] and chopstick[ (i+1) % 5]. This means
 . EATING THE RICE that the philosopher i has eaten and put down the
 . chopsticks on his sides. Then the philosopher goes
 signal( chopstick[i] ); back to thinking.
 signal( chopstick[ (i+1) % 5] );
 .
 . THINKING
 .
 } while(1);

Operating System Concepts – 10th Edition 1.73 Silberschatz, Galvin and Gagne ©2018
Dining Philosophers Problem
 Difficulty with the solution
 The above solution makes sure that no two neighboring philosophers can eat at the
same time. But this solution can lead to a deadlock. This may happen if all the
philosophers pick their left chopstick simultaneously. Then none of them can eat and
deadlock occurs.
 Some of the ways to avoid deadlock are as follows −
• There should be at most four philosophers on the table.
• An even philosopher should pick the right chopstick and then the left chopstick
while an odd philosopher should pick the left chopstick and then the right chopstick.
• A philosopher should only be allowed to pick their chopstick if both are available at
the same time.

Operating System Concepts – 10th Edition 1.74 Silberschatz, Galvin and Gagne ©2018
End
Reference Ch. 6

Operating System Concepts – 10h Edition Silberschatz, Galvin and Gagne ©2018

You might also like