I have a university assignment where I have to use threads to do some calculations. It boils down to one consumer with multiple producers --> each producer does one calculation, consumer adds it all together.
I'm having trouble synchronising this so that the producer will go into its critical section whenever a consumer has calculated their part and exited their critical section.
Here's the code I have so far:
CONSUMER
do
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&consumer, &mutex);
/*Do some stuff*/
pthread_mutex_unlock(&mutex);
count++;
} while(count < m); /*Where m is the number of producers*/
PRODUCER - Each producer only produces one value (Required - Assignment)
pthread_mutex_lock(&mutex);
/*Do some stuff*/
pthread_cond_signal(&consumer);
pthread_mutex_unlock(&mutex);
Is it possible to do this with only conditions and the mutex? If not, I'm assuming adding a semaphore would make things easier, but I'd rather try do it without.
Each producer must place their product into a global variable which must then be accessed by the consumer.
If there's anything else required, let me know.
SOLUTION : After reading John Bollinger's reply, I was able to fix my issue and create a working producer/consumer problem.
/******************CONSUMER*****************/
pthread_mutex_lock(&mutex);
while(count < m) /*While there are more threads*/
{
/*Makes producers wait for the consumer to be ready before
altering the global variable*/
if( predicate = -1 )
{
predicate = 0;
pthread_cond_signal(&producer);
}
/*Make consumer wait for the global variable to be altered*/
while(predicate == 0)
pthread_cond_wait(&consumer, &mutex);
/*Do some stuff with global variable*/
predicate = 0; /*Consumed*/
count++;
/*Tell a producer that the predicate has been consumed*/
pthread_cond_signal(&producer);
}
pthread_mutex_unlock(&mutex);
/********************PRODUCER********************/
pthread_mutex_lock(&mutex);
/*If the consumer is not ready yet, wait. I.e. if it's still
creating more threads*/
if(predicate == -1)
{
pthread_cond_wait(&producer, &mutex);
}
/*If there is already a product to be consumed, wait until
*consumed*/
while( predicate != 0 )
{
pthread_cond_wait(&producer, &mutex);
}
/*Do some stuff with global variable*/
/*Tell consumer that a product is ready to be consumed*/
pthread_cond_signal(&consumer);
pthread_mutex_unlock(&mutex);