Read Sections 6.1 and 6.2.1 of SG
item buffer[n]; int in = 0; /* next free buffer */ int out = 0; /* first full buffer */ int counter = 0; /* 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++;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?
int turn = 0; /* shared */ PROCESS 0: PROCESS 1: while(1) { while(1) { while (turn != 0) ; while (turn != 1) ;turn = 1; turn = 0; } }
int flag[2] = {0, 0}; /* shared variable */ PROCESS 0: PROCESS 1: while(1) { while(1){ flag[0] = 1; flag[1] = 1; while (flag[1]); while (flag[0]);flag[0] = 0; flag[1] = 0; } }
Skill: Understand what the critical section problem is.