Monitors, conditions, readers and writers locks Flashcards
What are monitor locks
only 1 thread can hold a lock
A thread acquires a lock when it starts to hold the lock
releases lock when stops holding lock
In Monitor locks what happens when a thread cant immediately acquire a lock?
Spins and repeatedly tests
Blocks and suspends thread and creates new thread
Spin = short time. Blocking = long time
How do you create a new condition
Condition = mutex.newCondition();//mutex = lock that its related to
how do you make a condition suspend
condition.await()
how can you notify threads that a change has occurred in a condition?
signal() or signalAll()
Does a thread have to retest condition if awaken and compete for the lock?
yes
What is a monitor?
combination of mutual exclusion locks and condition objects
What is lost wakeup problem?
1+ threads wait forever without realizing that the property for which they have been waiting has become true
enq code for Monitor?
public void enq(T x) {
lock.lock();
try {
while (count == items.length)
isFull.await();
items[tail] = x;
++count;
if (count == 1)
isEmpty.signal();
}
} finally {
lock.unlock();
}
}
How to avoid lost wakeup
ensure all processes are signaled
Specify timeout when waiting
What is allowed in the CS for reader-writer locks?
either multiple readers or a single writer
Reader-writer lock interface
public interface ReadWriteLock {
Lock readLock();
Lock writeLock();
}
What properties should the interface satisfy for the reader-writer lock?
No thread can acquire write lock while any thread holds either lock or read lock
no thread can acquire read lock while any other thread holds write lock
Class code for SimpleReadWriteLock
public class SimpleReadWriteLock implements ReadWriteLock {
boolean writer;
int readers;
Lock lock;
Condition condition;
Lock readLock, writeLock;
lock for ReadLock
class ReadLock implements Lock {
public void lock() {
lock.lock();
try {
while (writer)
condition.await();
readers++;
} finally {
lock.unlock();
}