132k views
0 votes
Here are the codes for producer and consumer problems.

Producer:

while (true) {

/* produce an item in next produced */

while (counter == BUFFER_SIZE) ;

/* do nothing */

buffer[in] = next_produced;

in = (in + 1) % BUFFER_SIZE;

counter++;

}

Consumer:

while (true) {

while (counter == 0)

; /* do nothing */

next_consumed = buffer[out];

out = (out + 1) % BUFFER_SIZE; counter--;

/* consume the item in next consumed */

}

counter++ could be implemented by Producer as

register1 = counter

register1 = register1 + 1

counter = register1

counter-- could be implemented by Consumer as

register2 = counter

register2 = register2 - 1

counter = register2

If we set the current value of "counter " as 4, when Producer and Consumer concurrently execute, what are the possible values of ‘’counter", please give an example for each value, point out which value is the right one and analysis the reasons for the wrong values.

User Gus Hecht
by
3.8k points

1 Answer

7 votes

Answer:

If a switch happens during counter++ or counter--, we will get a wrong value for the counter.

Step-by-step explanation:

counter++ counter--

register1 = counter register2 = counter

register1 = register1 + 1 register2 = register2 - 1

counter = register1 counter = register2

Lets consider this example, lets assume that counter=4, this simply means that there are 4 items which are produced already. Lets look at the following steps and value of counter after each step.

a) Producer process is updating counter++, this takes place at machine level, also, during that when it completed register1=counter counter=4

b) Supposing we have a context switch happen to consumer process and it is trying to update counter--, this takes place at machine level, also when it completed

register2=counter counter=4

register2=register2-1

counter=register2 counter=3

c) Lets assume that context switch happened back to producer process and it continues from where it stopped, look at step a

register1=register1+1

counter=register1 counter=5

This will make the value of counter variable to become 5. Consumption of one item is not reflected in the counter variable. To avoid this we need to allow the atomic execution of all these instructions. This implies completion of any updates on the counter, while others wait for its completion.

d) In the event a producer executes all these machine level instructions at once,then there is no inconsistency on this.

User Gilda
by
3.5k points