CS 336: Homework

Homework Assignment 4 (due Thurs Sept. 25)

Producer/Consumer Problem

There is a bounded circular buffer into which producer threads insert items and from which consumer threads remove items. If the buffer is empty, then the consumer threads must block until there are items for them to remove. Likewise, if the buffer is full, then the producer threads must block until there is space for them to insert items. The solution we used in class assumed consumers were going to consume 10 items each and that producers would produce at least as many items as the consumers would consume. But the program hang when the consumers stopped consuming, the buffer filled up, and the producers were waiting for it to empty to they could put more into it. Your assignment is to alter the code so that producers will produce a fixed number of items, but consumers will continue to consume until the buffer is empty and all of the producers have finished producing.

Coding: Create a hw4 directory with src and bin subdirectories. Download producers_consumers.c into the src directory. To compile, download the Makefile (again, into the src directory) and type make producers_consumers on the Terminal command line. To execute the code, type ../bin/producers_consumers. Because this producer/consumer mismatch version shown in class, it will get to a point and then hang. Type Ctrl-C on the command line to interrupt its execution once it gets to the point.

Copy producers_consumers.c to a new file producers_consumers_with_stopping.c and add to it code that allows the consumers to stop begging for food once the buffer is empty and the producers have stopped producing. You are encouraged to use the approach we discussed in class:

Test your solution thoroughly. Use lots of printf's when you run into code that hangs. In particular, put printf before calls to pthread_mutex_lock and pthread_cond_wait to see what thread is stuck on what blocking call. When you are happy with your implementation, email it to me.