Homework Assignment 4 (due Thurs Sept. 25)
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
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.
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:
- Use a global variable (protected by the mutex) that keeps track of how many producers have finished.
- In the
consumefunction check not only whether or not the buffer is empty but also whether or not all of the producers have finished.
consumer_threadso that it uses a while loop that depends upon a new return result from
consumeinstead of a for loop.
Test your solution thoroughly. Use lots of printf's when you run into code that hangs. In particular, put printf before calls to
pthread_cond_wait to see what thread is stuck on what blocking call. When you are happy with your implementation, email it to me.
- Put your name in the header comments of your producers_consumers_with_stopping.c. This is very important to me when I am grading the code.
- Comment your code! Part of your grade is dependent upon the presence of useful comments.
- If you cannot get the solution to work, contact me for help. I am available!