// buffer.cpp -- add any necessary code to implement producer/consumer // includes #include "vxWorks.h" #include "stdio.h" #include "stdlib.h" #include "semLib.h" #include "taskLib.h" #define STACK_SIZE 20000 #define BUFFER_SIZE 10 // use these to initialize the counting semaphores #define INITIAL_SPACES BUFFER_SIZE #define INITIAL_ITEMS 0 // use for cleanup and stopping of program #define ALL_STOP 1 #define ALL_GO 2 #define PROD_STOP 3 #define CONS_STOP 4 // buffer int buffer[BUFFER_SIZE]; // used to control circular buffer int in = 0; int out = 0; // task ids int tidProducer; int tidConsumer; volatile UINT8 runState = ALL_STOP; /* controls shutdown */ // use these ids to create counting semaphores SEM_ID itemsSemId; SEM_ID spacesSemId; // use to create binary semaphore to provide mutual exclusion for printf SEM_ID printSemId; void produce (void); void consume (void); void progStop (void); STATUS progStart (void); /************************************************************************* * * progStart - start the program. * * Create various semaphores and spawn various tasks, while doing * incredibly little error checking. * * RETURNS: OK */ STATUS progStart (void) { // setup counting semaphores // setup binary semaphore // get started runState = ALL_GO; tidConsumer = taskSpawn ("consumer", 200, 0, STACK_SIZE, (FUNCPTR) consume2,0,0,0,0,0,0,0,0,0,0); tidProducer = taskSpawn ("producer", 200, 0, STACK_SIZE, (FUNCPTR) produce2,0,0,0,0,0,0,0,0,0,0); return (OK); } void consume(void) { while (runState != CONS_STOP) { // delay task for random amount of time taskDelay((rand() % 100) + 1); // add code for consumer } runState = ALL_STOP; } void produce(void) { while (runState != PROD_STOP) { // delay for random amount of time taskDelay((rand() % 100) + 1); // add code for producer } // stop conumser runState = CONS_STOP; semFlush(itemsSemId); } /************************************************************************* * * progStop - stops the program * * Call this routine to end it all. */ void progStop (void) { runState = PROD_STOP; semFlush(spacesSemId); // Wait for everyone to finish up while (runState != ALL_STOP) taskDelay (1); // clean up semDelete (spacesSemId); semDelete (itemsSemId); semDelete (printSemId); printf ("BYE!TSCHUESS!ADIEU!\n"); }