Semaphores: Arvind Krishnamurthy Spring 2001
Semaphores: Arvind Krishnamurthy Spring 2001
1
How to use the lock ? Condition variables
n The lock provides mutual exclusion to the shared data n How to make RemoveFromQueue wait until something is on the
n Rules for using a lock: queue?
n Always acquire before accessing shared data structure n can’t sleep while holding the lock
n Always release after finishing with shared data n Key idea: make it possible to go to sleep inside critical section, by
atomically releasing lock at same time we go to sleep.
n Lock is initially free
n Simple example: a synchronized list n Condition variable: a queue of threads waiting for
something inside a critical section.
RemoveFromQueue() n Wait() --- Release lock, go to sleep, re-acquire lock
AddToQueue() {
{ lock.Acquire(); n release lock and going to sleep is atomic
lock.Acquire(); // lock before use if something on queue // can we wait?
put item on queue; // ok to access remove it;
n Signal() --- Wake up a waiter, if any
lock.Release(); // unlock after done lock->Release();
}
n Broadcast() --- Wake up all waiters
return item;
}
2
Implementing Monitors Producer-consumer with monitors
Condition full;
Condition empty;
n Wait() Queues Lock lock;
Summary Question 1:
n Template for using monitors: n Why does wait need to be an atomic “unlock + sleep”
operation?
Question 2: Question 3:
n If wait does not automatically acquire the lock when it n Does the waker require mutex?
returns, does that lead to errors?
3
Question 4: Readers/writers problem
n Is it correct to: change state with mutex, but signal without n Motivation
the lock? n shared database (e.g., bank balances / airline seats)
n Two classes of users:
n Readers --- never modify database
lock.Acquire(); lock.Acquire();
n Writers --- read and modify database
} lock.Release();
n Constraints
lock.Release(); signal(cond);
n Readers can access database when no writers (Condition okToRead)
n Writers can access database when no readers or writers (Condition
okToWrite)
n Only one thread manipulates state variable at a time