In small groups, you will come up with a solution to the
producer consumer problem with a fixed size buffer. Here are
some of the parameters of the problem:
- There is a fixed-size shared buffer of size N. Producer and Consumer
threads access it a circular queue of items: producers add to the
current end of the queue, consumers remove items from the current
front of the queue.
- There are some number of producer threads (m), and some
number of consumer threads (m).
- Each producer thread produces the same number of items (k).
Each thread repeats the following k times:
- produce the next item
- add it to the end of the buffer
- Each consumer thread consumes the same number of items (k).
Each thread repeats the following k times:
- remove the next item from the buffer
- consumes it
In your group you are going to do the following:
- Come up with a solution to synchronize the actions of producer and
consumer threads so that all items added to the end of the buffer
are added correctly and all items removed from the buffer are
removed correctly given multiple concurrent threads.
- are there actions that need to be made atomic
(require mutually exclusive access)?
- are there any scheduling types of synchronization necessary?
- what synch primitives do you need and how are they used (by whom
and when)?
- map out in PSEUDOCODE the producer and consumer main loops
- run your pseudocode solution by me or a ninja before moving on
- Next, run update31 to get starting point code
~/cs31/inclass/13/prodcons.c #implement your solution in here
There are already routines to add and remove items from the circular
buffer, and a debug print_buffer function (call fflush(stdout) after
any debug output to force it to the terminal window)
Implement code in main to spawn producer and consumer tids
Implement the producer and consumer main loop functions
You could make a call to usleep to simulate the produce an item
and consume an item steps. You could even use the C random library to
generate a random number of microseconds to sleep each time you call usleep.
See the man pages for srand, rand, and usleep. (and the max program from
inclass/12/ has an example of using srand and rand)
Add all synchronization necessary to synchronize the actions of
concurrent producer and consumer threads
Shared global buffer state:
---------------------------
static char *buff; // the buffer
static int N; // total buffer capacity
static int size; // current num items in the buffer
static int next_in; // next insertion index in the buffer
static int next_out; // next remove index in the buffer
static int num_items; // number of items each tid should produce or consume
Some
Pthread Resources