Solution to the Producer-Consumer problem using Message Passing
Message Passing allows us to solve the Producer-Consumer problem on distributed systems. In the problem below, an actual buffer does not exit. Instead, the producer and consumer pass messages to each other. These messages can contain the items which, in the previous examples, were placed in a buffer. They can also contain empty messages, meaning that a slot in the "buffer" is ready to receive an new item. In this example, a buffer size of four has been chosen. The Consumer begins the process by sending four empty messages to the producer. The producer creates a new item for each empty message it receives, then it goes to sleep. The producer will not create a new item unless it first receives an empty message. The consumer waits for messages from the producer which contain the items. Once it consumes an item, it sends an empty message to the producer. Again, there is no real buffer, only a buffer size which dictates the number of items allowed to be produced.
BufferSize = 4; Producer() { int widget; message m; // message buffer while (TRUE) { make_item(widget); // create a new item receive(consumer, &m); // wait for an empty message to arrive build_message(&m, widget); // make a message to send to the consumer send(consumer, &m); // send widget to consumer } } Consumer() { int widget; message m; for(0 to N) send(producer, &m); // send N empty messages while (TRUE) { receive(producer, &m); // get message containing a widget extract_item(&m, widget); // take item out of message send(producer, &m); // reply with an empty message consume_item(widget); // consumer the item } }
IPC Home Subway Problems Producer/ Page Map Consumer