0% found this document useful (0 votes)
17 views

Semas

Semaphores are used for process synchronization and protecting shared resources. They allow processes to signal and wait for each other. A semaphore is initialized to a nonnegative value and wait operations decrement while signal operations increment the value. Common problems solved using semaphores include the producer-consumer problem, reader-writer problem, and dining philosophers problem. The producer-consumer problem uses semaphores on a buffer to allow a producer to signal a consumer when an item is added and a consumer to signal a producer when an item is removed.

Uploaded by

mayank singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Semas

Semaphores are used for process synchronization and protecting shared resources. They allow processes to signal and wait for each other. A semaphore is initialized to a nonnegative value and wait operations decrement while signal operations increment the value. Common problems solved using semaphores include the producer-consumer problem, reader-writer problem, and dining philosophers problem. The producer-consumer problem uses semaphores on a buffer to allow a producer to signal a consumer when an item is added and a consumer to signal a producer when an item is removed.

Uploaded by

mayank singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 116

Semaphores

Ref: William Stallings,Galvin, Naresh Chauhan


G.Anuradha
What is a semaphore?
• Popular tool for process synchronization
• Used to protect any resource such as global
shared memory that needs to be accessed and
updated by many processes
• Analogy- allotment of seminar room for
various activites of college.

03/07/24
Principle of a Semaphore
For signaling semaphores are used
– For sending a signal semSignal (s) is used
– For receiving a signal semWait(s) is used
• First defined by Dijkstra
• Semaphore is a variable
– A semaphore may be initialized to a nonnegative integer value.
– The semWait operation decrements the semaphore value.
– The semSignal operation increments the semaphore value.
– wait (S) {
while S <= 0
; // no-op
S--;
}
– signal (S) {
S++;
}

03/07/24
Definition of semaphore
Types of Semaphores
• Binary semaphore:-takes value 0 and 1-used for
resource having a single instance
• Counting Semphore:- when there are more than one
process.
• Mutex:-similar to binary semaphore but the key
difference is that the mutex is locked and unlocked
by the same process
Classical Synchronization problems
• Producer consumer problem
• Reader-writer problem
• Barber shop
• Dining philosopher
I. Producer-Consumer
Imagine a chef cooking items
and putting them onto a conveyor belt

43 43
Producer-Consumer
Imagine a chef cooking items
and putting them onto a conveyor belt

Now imagine many such chefs!

44
Producer-Consumer
Imagine a chef cooking items
and putting them onto a conveyor belt

Now imagine many such chefs!

45
Producer-Consumer
Imagine a chef cooking items
and putting them onto a conveyor belt

Now imagine many such chefs!

Now imagine a customer picking items off the conveyor belt

46
Producer-Consumer
Imagine a chef cooking items
and putting them onto a conveyor belt

Now imagine many such chefs!

Now imagine many such customers picking items off the conveyor belt!

47
Producer-Consumer
Imagine a chef cooking items
and putting them onto a conveyor belt

Now imagine many such chefs!

Now imagine many such customers picking items off the conveyor belt!

48
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr

49
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr

50
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr

51
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr

52
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr
53
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr
54
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr

removePtr
55
Producer-Consumer
Chef = Producer
Customer = Consumer

BUFFER FULL: Producer must be blocked!

insertPtr

removePtr
56
Producer-Consumer
Chef = Producer
Customer = Consumer

insertPtr
removePtr

57
Producer-Consumer
Chef = Producer
Customer = Consumer

removePtr

insertPtr

58
Producer-Consumer
Chef = Producer
Customer = Consumer

removePtr

insertPtr

59
Producer-Consumer
Chef = Producer
Customer = Consumer

removePtr

insertPtr

60
Producer-Consumer
Chef = Producer
Customer = Consumer

removePtr

insertPtr

61
Producer-Consumer
Chef = Producer
Customer = Consumer

removePtr

insertPtr

62
Producer-Consumer
Chef = Producer
Customer = Consumer

removePtr

insertPtr

63
Producer-Consumer
Chef = Producer
Customer = Consumer

BUFFER EMPTY: Consumer must be blocked!

removePtr
insertPtr

64
Producer Consumer problem
Infinite buffer
Solution of Producer consumer
using Semaphores
• Examples
– Compiler is a producer producing object code
– Assembler is a consumer that takes object code
– Printing a file is a producer process
– Printing file on the printer is a consumer process

03/07/24
Requirements to solve producer
consumer problem
• Producer should not produce an item when buffer is full
• Consumer should not consume when buffer is empty
• Producer and consumer should not try to access and update the buffer at
the same time
• Producer is full and item is produced then producer should be blocked
• If consumer is ready and buffer is empty then consumer should be
blocked
• When a consumer process consumes an item, that is, a slot in the buffer is
created the blocked producer must be signaled about it.
• When a producer process produces an item in the empty buffer, blocked
consumer process must be signaled about it.

03/07/24
• Producer Consumer problem can be solved by
placing a semaphore on the buffer.
• Two more semaphores are taken which will
count the number of empty slots and full slots
in the buffer.
• 3 semaphores are used in the solution
– empty semaphore initialized to n where n is the
number of empty slots in the buffer
– full semaphore initialized to zero
– buffer-access semaphore initialized to one
Algorithms for producer-consumer problem’s
solution with Semaphore
• The producer after producing the item waits
on the empty semaphore to check for an
empty slot
• Then it waits for the Buffer-access semaphore
to check whether any other process is
accessing it
• After getting permission it stores
• After storing it signals the buffer_access so
that any other process in wait can access the
buffer.
What is a reader writer problem?
Read Write
Read Y N
Write N N

Where was it used?


Reader-Writer problem using Semaphore

Case 1: Readers have the priority


One reader process is inside the critical section and multiple writer
processes arrive, then they must wait on the semaphore.

One writer process is inside the critical section and multiple reader
processes arrive, then they must wait on the semaphore.

One reader process is inside the critical section and multiple reader
processes arrive, then they will not wait on the semaphore.

One writer process is inside the critical section and multiple writer
processes arrive, then they must wait on the semaphore.
Reader-Writer problem using Semaphore
ReadCount : integer variable as counter for reader processes;
initialized as 0.

Sem_ReadCount: semaphore for ReadCount; initialized as 1

Sem_ReadWrite: semaphore for mutual exclusion between reader


and writer processes; initialized as 1
Algorithms for reader-writer problem’s solution
with semaphore: Readers have priority
Reader-Writer problem using Semaphore
 Case 2: Writers have the priority
Solution must be designed such that long queue of readers are not
allowed where writers are waiting.
For this another semaphore Sem_restrict is used which will restrict
the readers from entering the queue.
If no writer is accessing the CS and new writer arrives then it
will also wait on Sem_restrict so that readers do not monopolize and
writers can start
Scenarios in writers having priority
 If no writer is accessing the CS and new writer
arrives then it will also wait on Sem_restrict so that
readers do not monopolize and writers can start.
 Once a writer enters the Cs and there are writers
and readers waiting then only writers will be
allowed to access.
 After all writers finish their work, if a reader
appears then the reader will be given access first.
Algorithm for writers having
priority
Reader() Writer()
{ {
While(true){ While(true){
Wait(Sem_readerWait); Wait(Sem_writecount)
Wait(Sem_restrict); writecount++
Wait(Sem_readcount) if(writecount==1)
readcount++ wait(sem_restrict);
if(readcount==1) signal(sem_writecount);
wait(sem_readwrite); wait(sem_readwrite);
signal(sem_readcount); Perform the write operation
signal(sem_restrict); signal(sem_readwrite)
signal(sem_readerWait); wait(sem_writeCount);
Perform the read operation writecount--;
wait(sem_readCount); if(writecount==0)
readcount--; signal(sem_restrict)
if(readcount==0) signal(sem_writecount)
signal(sem_readwrite) }}
signal(sem_readcount)
}}
Case 3: No priority
Reader() Writer
{ {
While(true){ while(true){
Wait(sem_count) wait(sem_count);
If (writecount>0) OR writecount++;
readcount = = 0) signla(Sem_count);
{ wait(sem_readwrite);
Signal(sem_count); Perform the write operation
Wait(sem_readcount); wait(sem_count);
Wait(sem_count); writecount--;
} signal(sem_count);
ReadCount--; signal(sem_readwrite);
If(readcount==0) }}
signal(sem_readwrite)
signal(sem_count);
}}
Barbershop Problem
• 3 barbers, each with a barber chair
– Haircuts may take varying amounts of time
• Sofa can hold 4 customers, max of 20 in shop
– Customers wait outside if necessary
• When a chair is empty:
– Customer sitting longest on sofa is served
– Customer standing the longest sits down
• After haircut, go to cashier for payment
– Only one cash register
– Algorithm has a separate cashier, but often barbers
also take payment
• This is also a critical section
II. Reader-Writer Problem
• A reader: read data
• A writer: write data
• Rules:
– Multiple readers may read the data simultaneously
– Only one writer can write the data at any time
– A reader and a writer cannot access data simultaneously
• Locking table: whether any two can be in the critical section
simultaneously
Reade Writer
r
Reade OK No
r
Writer No No 80
III. Dining Philosophers: an
intellectual game

81
Problem Statement
• Five philosophers eat then think forever
– They never sleep nor relieve themselves!
– They do not behave altruistically
• They eat at a communal table
– It has a single bowl of tangled spaghetti
– Five plates each with a single fork to the left of their plate
– To eat a philosopher must have two forks, their own and
that of their neighbour’s to the right
– If a philosopher is unable to eat they resume thinking
Ramifications
• Deadlock
– All philosophers decide to eat at same time
– They all pick up one fork
– None of them can eat hence the system comes to
a halt
• Starvation
– Some philosophers think for such a short time and
contrive to put their forks down in such a way that
no other philosophers have the opportunity to
pick up the two forks they require to eat
Deadlock - Pictorially
Starvation - Pictorially
Naïve Solution
• Unconstrained picking up and putting down of
forks causes problems
– So put down in the reverse order of picking up
• Manage the entry and exit of philosophers to
the table by means of a Butler process that
entry and exit is orderly
• Each fork is a process
– Accessed either from left or right hand
Deadlocks
• Each philosopher has their left fork
• BUT
• Cannot get a right fork

• Butler did nothing


– Needs to control access to table so that there is
always one empty seat
– Ensures one philosopher can eat
Butler Controls
• No more than 4 philosopher can sit at the
table (enter)
• Once 4 philosophers seated then Butler only
lets people exit (get down) from the table
Problems with Semaphores
• Incorrect usage of semaphores leads to timing
errors
• Timing errors occur only if some particular
execution sequence takes place.(rare)
• InCorrect use of semaphore operations
– signal (mutex) …. wait (mutex) (multiple CS)
– wait (mutex) … wait (mutex) (deadlock)
– Omitting of wait (mutex) or signal (mutex) (or
both)
Monitors
• A high-level abstraction (ADT) that provides a convenient and effective mechanism for
process synchronization
• Only one process may be active within the monitor at a time
• Has one or more procedure, initialization sequence, local data
• Local data variables are accessible only by the monitor’s procedures and not by any external
procedure

monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }

procedure Pn (…) {……}

Initialization code ( ….) { … }



}
}
Schematic view of a Monitor

91
Condition Variables
• Synchronization is supported by the use of condition variables that are contained
and accessible only within the monitor
• condition x, y;

• Two operations on a condition variable:


– x.wait () – Suspends execution of the calling process on condition x. monitor is
available for use by another process
– x.signal () – resumes execution of some process suspended after a wait on the
same condition. one of processes (if any) that is invoked

92
Monitor with Condition Variables

93
Monitors for Producer consumer
problem
• Monitor module used to control the buffer to
store and retrieve characters.
• Condition variables
– Not full :- TRUE then there is room to add atleast
one character to the buffer
– Not empty :- TRUE then there is atleast one
character in the buffer

94
Monitors for Producer consumer
Bounded Buffer problem
Solution to Dining Philosophers

monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];’/* hungry but is unable to obtain forks*/
/* A philosopher can set state[i]=eating only if state (i+4)%5 and (i+1)%5 are not
eating */
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);
}
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;
}
}

98
Solution to Dining Philosophers (cont)

• Each philosopher I invokes the operations pickup()


and putdown() in the following sequence:

dp.pickup (i)

EAT

dp.putdown (i)

No two neighbours eat simultaneously and no deadlocks


will occur. But a philosopher can starve to
death…………………………

99
Synchronization Hardware
• One simple solution to the critical section
problem is a lock
Hardware solutions
• In a uniprocessor environment, the interrupts
could be prevented from occurring while a
shared variable was modified(nonpreemptive)
• TestAndSet() and Swap() instructions are used
in multiprocessor environment
Definition of the TestAndSet()

The semantics of test-and-set are:


◆ Record the old value and
◆ Set the value to indicate available and
◆ Return the old value
Compare and Swap
Compare and swap
• global variable lock is declared and initialized
to 0.
• the first process that invokes
compare_and_swap sets lock to 1
• subsequent calls will not succeed
• when a process exits CS sets lock to 0 so that
other process can enter
• Data Structures are first initialized to false
• Pi can enter CS only if waiting[i] and key are
both false
• key becomes false only in test and set is false
• waiting[i] can become false only if another
process leaves its critical section; only one
waiting[i] is set to false maintaining the
mutual exclusion requirement
University questions
1. In a typical process state transition diagram. Clearly state under what
condition the following state transition occur?
1. running to ready
2. running to waiting
3. waiting to ready.
2. Consider a system running 10 I/O bound tasks and 1 CPU bound task
issues an I/O operation once for every millisecond of CPU computing and
that each I/O operation takes 10 ms. context switch takes 0.1ms and all
processes are long running tasks. what is the CPU utilization for RR
scheduler when
1. the quantum is 1ms
2. the quantum is 10ms
3. Suggest the implementation of binary semaphore that avoids the buzy waiting
4. What is a thread? Explain ULT and KLT
• What are preemptive and nonpreemptive
algorithms
• write short notes on race conditions

You might also like