Monitors
- Invented by Tony Hoare …
Monitors
- Invented by Tony Hoare in 1974
-
Like a C++ class
- Consists of vars and procedures
- Only one thread in a monitor at a time (automatic mutual exclusion)
- Specifal type of variable, called condition variable
- wait
- signal
- broadcast
- No public variables allowed (must call procedures to access variables)
- Consists of vars and procedures
-
A high-level abstraction that provides a convenient and effective mechanism for process synchronization
-
Only one process may be active within the monitor at a time
-
Condition Variables
- Automatic unlock and lock for mutual exclusion
- cond.wait () - Thread is put on queue for “cond”, goes to sleep.
- cond.signal () - If queue for “cond” not empty, wake up on thread
- cond.broadcast() - Wake up all threads waiting on queue for “cond”
-
Semantics of Signal
- Signal and Wait (Hoare-style)
- Signaler passes lock, CPU to waiter; waiter runs immediately
- Waiter gives lock, CPU back to signaler when
- It exits critical section
- Or, it waits again
- Signal and Continue (Mesa-style)
- invented by Xerox company
- signaler continues executing
- waiter put on ready queue
- when waiter actually gets to run
- May have to wait for lock again
- State may have changed! Use “while”, not “if”
- Used in Java, Pthread
- Monitor types
- Signal and Wait (Hoare-style)
-
Bounded Buffer by Monitor
In Bounded Buffer,
Enqueue (int v)
{
while( size == MAX_SIZE) full.wait();
BUFFER[tail] = v;
tail = (tail+1) % MAX_SIZE;
size++;
if (size ==1) empty.signal();
}
Deque (int v)
{
while(size==0) empty.wait();
int i = head;
head = (head+1) % MAX_SIZE;
size--;
if ( size == MAX_SIZE-1) full.signal();
return BUFFER[i];
}
- Hoare Style
- Monitor Implementation (using semaphores)
- Need mutual exclusion semaphore mutex (init to 1) so that only one process is active within monitor
- Need a semaphore next (next to exit) for the signaling process to suspend itself
- initialized to zero
- next_count is number of processes blocked on next
- Before exiting a procedure, process must either:
- Signal other waiting processes in monitor next before exiting
- Signal mutex and exit
- Monitor Implementation
- Monitor Implementation (using semaphores)
Procedure F:
wait(mutex);
...
body of F
...
if (next_count > 0) signal(next);
else signal(mutex);
end;
+ Condition Variable Implementation
Share
Donation
如果覺得這篇文章對你有幫助, 除了留言讓我知道外, 或許也可以考慮請我喝杯咖啡, 不論金額多寡我都會非常感激且能鼓勵我繼續寫出對你有幫助的文章。
If this blog post happens to be helpful to you, besides of leaving a reply, you may consider buy me a cup of coffee to support me. It would help me write more articles helpful to you in the future and I would really appreciate it.