CS31 Week 13
In-class Exercise:

parallel producer/consumer in pthreads
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:

In your group you are going to do the following:

  1. 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.
    1. are there actions that need to be made atomic (require mutually exclusive access)?
    2. are there any scheduling types of synchronization necessary?
    3. what synch primitives do you need and how are they used (by whom and when)?
    4. map out in PSEUDOCODE the producer and consumer main loops
    5. run your pseudocode solution by me or a ninja before moving on

  2. 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