5.4.2 Producer-Consumer with Monitors(1/4) ★ program producer。 nsumer monitor boundedbuffer: char buffer [; / space for N items * int nextin, nextout: / buffer pointers * intc。unt / number of items in buffer * cond notfull, notempty; /*c。 ndition variables for synchronizati。n*/ void append (char x) if (count wait(notfull)i / buffer is full: avoid overflow * buffer [nextin =x; nextin =(nextin + 1) N; c。unt+ / one more item in buffer * A signal(notempty) / resume any waiting consumer * void take (char x) if (count = 0) wait(notempty); / buffer is empty; avoid underflow * x= buffer [nextout nextout =(nextout +1)% N; count-- / one fewer item in buffer * signal(notfull)i / resume any waiting producer * /★ monitor body*/ nextin =0: nextout =0: count =0; / buffer initially empty
5.4.2 Producer-Consumer with Monitors(1/4) 17
5.4.2 Producer-Consumer with Monitors( 2/4) void producer ( char x while (true) produce(x) append(x)i void consumer ( char x while (true) take(x); consume(x)i void main() parbegin (producer, consumer)i Figure 5.16 A Solution to the Bounded-Buffer Producer/Consumer Problem Using a monitor
5.4.2 Producer-Consumer with Monitors(2/4) 18
5.4.2 Producer-Consumer with Monitors( 3/4) Hansen管程 ■ Hoare管程 acquire( 1. acquire( xwa1t()T1进入等待 xwaito) T1进入等待 T2进入管程|1.acu1re( T2进入管程|1. acquire() T2进入等待x.s1gna1( x. signal() T1恢复管程执行 T2退出管程1, release( 1. release()T1结束 T2恢复管程执行 T1恢复管程执行 1. release ( l. released)
5.4.2 Producer-Consumer with Monitors(3/4) 19