while(true){
/*produce an item in nextProduced */
while(counter == BUFFER_SIZE)
;/*do nothing*/
buffer[in] = nextProduced;
in = (in+1)%BUFFER_SIZE;
counter++;
}
以上是生产者进程代码
消费者进程代码
while(true){
while(counter == 0)
;/* do nothing */
nextConsumed = buffer [out];
out = (out+1)%BUFFER_SIZE;
count --;
/* consume the item in netxCounsumed */
虽然生产者和消费者各自都正确,但是并发执行时,两者同时执行count++和count--时,counter的值就未知了,因此需要一段时间内只有一个进程能够操作变量counter,这就需要进程同步了