Process Coordination & Semaphores

These are the modified Producer and Consumer programs, which now use the counter variable (boldfaced below):

item nextProduced;
while( true ) {
    /* Produce an item and store it in nextProduced */
    nextProduced = makeNewItem( . . . );
    /* Wait for space to become available */
    while( counter == BUFFER_SIZE ) ; /* Do nothing */
    /* And then store the item and repeat the loop. */
    buffer[ in ] = nextProduced;
    in = ( in + 1 ) % BUFFER_SIZE;
    counter++;
}

item nextConsumed;
while( true ) {
    /* Wait for an item to become available */
    while( counter == 0 ) ; /* Do nothing */
    /* Get the next available item */
    nextConsumed = buffer[ out ];
    out = ( out + 1 ) % BUFFER_SIZE;
    counter--;
    /* Consume the item in nextConsumed
         ( Do something with it ) */
}