Producer–Consumer Problem

Task

Implement communication between producer and consumer processes using a bounded buffer of limited length. Based on the number of command-line parameters, the initial process creates the corresponding number of producer processes and one consumer. Each producer takes one string provided via the command line and sends it to the consumer through the buffer character by character (see the example execution at the bottom of the page). The consumer receives characters one by one, and when it has received all characters (including the string terminator character '\0' sent by producers), it prints all received characters and terminates.

Suggested Solution Structure

Data shared by producers and the consumer (place them in a shared memory segment that must be created separately):

Structure of the producer process

producer process
   read a string from the keyboard into array s[]
   i = 0
   do
      wait_SLOTS
      wait_WRITE
      M[IN] = s[i]
      IN = (IN + 1) mod 5
      signal_WRITE
      signal_MESSAGES
      i = i + 1
   until end of string
end.

Structure of the consumer process

consumer process
   i = 0
   do
      wait_MESSAGES
      s[i] = M[OUT]
      OUT = (OUT + 1) mod 5
      signal_SLOTS
      i = i + 1
   until the end of all strings
   print the string from array s[] to the screen
end.

Notes

The end-of-string marker must also be transmitted using the buffer so the consumer can know when a string ends. The consumer should print received characters and terminate only after it has received all end-of-string markers. “Slow down” the producer process by calling sleep(1) once inside the loop.

Example output and program execution

(Two strings are provided: 12345678 and abcdef, so two producer processes are created.)

# ./a.out 12345678 abcdef
PRODUCER1 -> 1
PRODUCER2 -> a
CONSUMER <- 1
PRODUCER1 -> 2
CONSUMER <- a
PRODUCER2 -> b
CONSUMER <- 2
PRODUCER1 -> 3
CONSUMER <- b
PRODUCER2 -> c
CONSUMER <- 3
PRODUCER1 -> 4
CONSUMER <- c
PRODUCER1 -> 5
CONSUMER <- 4
PRODUCER2 -> d
CONSUMER <- 5
PRODUCER1 -> 6
CONSUMER <- d
PRODUCER2 -> e
CONSUMER <- 6
PRODUCER2 -> f
CONSUMER <- e
PRODUCER1 -> 7
CONSUMER <- f
PRODUCER2 ->
CONSUMER <- 7
PRODUCER1 -> 8
CONSUMER <-
PRODUCER1 ->
CONSUMER <- 8
CONSUMER <-

Received: 1a2b3c45d6ef78
#