I have an assignment to complete and got stucked at one point . Is the classical producer-consumers problem with 1 producer, n multiple consumers and a MAX number of items produced.
I have to use Condition Variables. I have 2 big doubts:
1- How to stop the consumers when all the items are created by the producer? I mustn't use global variables to solve this.
My problem is that all the consumers remain waiting for the producer that has just finished its execution because he produced all the items.
2-Each item has a random id that represents the id of the consumer that is supposed to consume it. So a consumer can only consume its own item (marked by the producer randomly at the beginning). How to implement this with condition variables.
My code works with 1 prod and 1 cons. When I have more than 1 consumer I don't know how to terminate the consumers thread when all the items are produced.
This is my code now:
static void * producer (void * arg)
{
ITEM item;
int j = 1;
while (j <= NROF_ITEMS)
{
rsleep (PRODUCER_SLEEP_FACTOR);
item = create_item(j);
pthread_mutex_lock (&mutex);
while(item_counter == BUFFER_SIZE)
pthread_cond_wait(¬_full_condition, &mutex);
put(item);
printf("%04x\n", item); // write info to stdout
pthread_cond_signal (¬_empty_condition);
pthread_mutex_unlock (&mutex);
j++;
}
pthread_exit(0);
// TODO:
// * inform consumers that we're ready
//HERE I NEED TO STOP THE CONSUMER THREAD
}
static void * consumer (void * arg)
{
ITEM item; // a consumed item
int id;
int * argid;
argid = (int*) arg;
id = *argid;
free(arg);
while (i < NROF_ITEMS)
{
rsleep (100 * NROF_CONSUMERS);
pthread_mutex_lock (&mutex);
while(item_counter == 0)
pthread_cond_wait(¬_empty_condition, &mutex);
printf("\n C%d signalled by the producer",id);
item = get_after_check();
printf("%*s C%d:%04x\n", 7*id, "", id, item);
pthread_cond_signal (¬_full_condition);
pthread_mutex_unlock (&mutex);
i++;
}
pthread_exit(0);
}