A new template for Lab 5 (Consumer Producer Assignment) based on the old one.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

86 lines
1.9 KiB

/***** Global Includes *****/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/***** Local Includes *****/
#include "queue.h"
#include "thread.h"
/***** Constants *****/
#define TIME_TO_PRODUCE 1 // second
#define TIME_TO_CONSUME 1 // second
#define LOOP 10
void producer(queue *q)
{
for (int i = 0; i < LOOP; ++i)
{
/*
* TODO for students: obtain the lock and release the lock somewhere
*/
while (queueIsFull(q));
enqueue(q, i+1);
printf ("producer: produced %d th.\n",i+1);
sleep_microseconds(PRODUCER_SLEEP_S * 1000000);
}
}
void consumer(queue *q)
{
// Simulate consumers' random arrival
sleep_microseconds((rand()%LOOP) * 1000000);
/*
* TODO for students: obtain the lock and release the lock somewhere
*/
while (queueIsFull(q));
sleep_microseconds(CONSUMER_SLEEP_S * 1000000);
printf ("------------------------------------>consumer: recieved %d.\n", dequeue(q));
}
int main()
{
// Initialize the queue. If the queue fails to initialize, kill the program.
queue *fifo = queueInit();
if (fifo == NULL)
{
fprintf(stderr, "main: Queue Init failed.\n");
exit (1);
}
// Seed the random number generator using the system clock.
unsigned int iseed = (unsigned int) time(NULL);
srand(iseed);
// Start one producer thread and as many consumer threads as specified above.
thread_t pro, con[LOOP];
create_thread(&pro, producer, fifo);
for (int i = 0; i < LOOP; ++i)
{
sleep_microseconds((rand() % 2) * 1000);
create_thread(&con[i], consumer, fifo);
}
// Let the producers and consumers finish before cleaning up.
wait_for_threads(&pro, 1);
wait_for_threads(con, LOOP);
// Clean up the queue.
queueDestroy(fifo);
#ifdef WINDOWS
// If this is running in Windows, execute the "pause" shell command so that
// the command prompt window doesn't close after this program finishes.
system("pause");
#endif
return 0;
}