7.1.1 The Bounded Buffer Problem
We can solve the
bounded buffer problem by encapsulating the functionality of the
counter in semaphores, as illustrated by the code below.
---------------------
/* All these variables and types are shared */
#define BUFFER_SIZE 10
typedef struct
{
/* declare desired fields for the buffer item type */
} item ;
item buffer[BUFFER_SIZE] ; // the buffer implemented as an array of items
int in=0, /* in == where the next item is added */
out=0; /* out == where the next item is removed */
semaphore full(0), /* full->value == the number of full buffers */
empty(BUFFER_SIZE) ; /* empty->value == the number of empty buffers */
---------------------
Producer's Code
do
{
/* produce an item in nextp */
wait (empty) ;
buffer[in]= nextp ;
in = (in + 1) % BUFFER_SIZE ;
signal(full) ;
} while (true) ;
---------------------
Consumer's Code
do
{
wait (full) ;
nextc = buffer[out] ;
out = (out + 1) % BUFFER_SIZE ;
signal(empty) ;
/* consume nextc */
} while (true) ;
---------------------