B424 Parallel and Distributed Programming

Producers and Consumers

General model

// global variables
some_type data[max];
int counter = 0;

Producer()
{
  while (true) {
    item = Produce_item();
    while (!Deposit(item)) ;
  }
}

Consumer()
{
  while (true) {
    while (!Fetch(item));
    Consume(item);
  }
}

int Deposit(some_type item)
{
  if (Data_is_full())
    return 0;
  else {
    data[counter++] = item;
    return 1;
  }
}

int Fetch(some_type &item)
{
  if (Data_is_empty())
    return 0;
  else {
    item = data[--counter];
    return 1;
  }
}

int Data_is_full()
{ return (counter == max); }

int Data_is_empty()
{ return (counter == 0); }

The code of the program using pthreads:

producer_consumer.cc
producer_consumer.h