Reading: Tanenbaum pages 33-38 (Section 2.2)
item buffer[n]; int in,out,counter;
in
points to the next free bufferout
points to the first full buffer counter
contains the number of full buffers.
Pool is empty when counter = 0
and is full when
counter = n
.
Producer loop:
produce an item in nextp while (counter == n) ; buffer[in] = nextp; in = (in+1) % n; counter++; in = (in+1) % n; counter++;Consumer loop:
while (counter == 0) ; nextc = buffer[out]; out = (out+1) % n; counter--; consume the item in nextc
Although each routine is correct by itself, they do not function
correctly when run concurrently. How are
counter++
and counter--
implemented?
PROCESS 1: PROCESS 2: while(TRUE) { while(TRUE) { while (turn != 0) ; while (turn != 1) ;turn = 1; turn = 0; } }