CS 471

Assignmnet #3

Due Midnight, Thursday March 21, 2013

 

Write the following program (You may use any programming language that supports threads, e.g. C, C++, Java):

 

The program creates two types of threads:  Producers & Consumers interacting via a common Buffer.

 

Syntax:

 

sync999 [N]

 

Where N is an optional argument <= 9.  The default value of N is 9 (that is why it is named sync999)

 

There are:

 

N Producer threads,

N Consumer threads and

N Buffer slots.

 

A producer produces N items in N buffer slots then exits. A consumer consumes N items from N buffer slots then exits.

The production or consumption times of an item is R seconds, where R is a random number between 1 and N.

 

·       Buffer:

A buffer has N slots, each slot has two fields:

      S (State) and T (Thread).

 

         

         Slot state S[i] has 4 possible values:

           0 Free

           1 Producing

           2 Ready to consume

           3 Consuming

T[i] store the produced/consumer thread number (1 to N) currently producing/consuming an item at slot i.

 

Buffer Initialization:

 

for i = 1 to N {

S[i] = 0

T[i] = 0

}

 

·       Producer threads  P  (1, ...N):  Each thread  P produces N items.

 

ProducedItemCount = 0

While (ProducedItemCount < N) {

          Find k such that S[k] == 0 (If no such k, sleep R seconds and try again):

           S[k] = 1, T[k] = P

           Sleep R seconds

           S[k] = 2 , T[k] = 0

           ProducedItemCount++

                     Display:

                           Buffer Slot number (k)

                           Production time (R)

}

Display thread total  life span.

 

 

·       Consumer thread  C (1, ...N): Each thread consumes N items.

 

ConsumedItemCount = 0

While (ConsumedItemCount < N) {

          Find k such that S[k] == 2 (If no such k, sleep R seconds and try again):

           S[k] = 3, T[k] = C

           Sleep R seconds

           S[k] = 0 , T[k] = 0

           ConsumedItemCount++

                     Display:

                           Buffer Slot number (k)

                           Consumption  time (R)

}

Display thread total  life span.

 

   

 

·       The main thread:

§  Periodically (every N seconds), Displays the state of the buffer slots (S[i] and T[i]) .

§  When all threads exits, display  the following information about each thread:

o   Slot numbers used to produce/consume the items.

o   Items production/consumption times

o   Thread life span.

§  Display the program life span and exits.

 

 

 You may execute my solution at:

http://www.cs.odu.edu/~cs471w/spring13/assignments/a3/wahab

EXAMPLES:

 

% ~/public_html/spring13/assignments/a3/wahab> sync999 3

 

% ~/public_html/spring13/assignments/a3/wahab> sync999

 

 

See  SamplOutputs  File