I am trying to get over my fear of multithreading programming and teaching myself to code using POSIX. I wrote a small version of the consumer producer problem. I am hoping I can get some feedback if it works (I think it does, as I traced the threads when my for
loop was at 20 and it made sense) and what I should do to improve my code.
The semaphore starts at 4, the consumer waits one second, and then consumes a semaphore. The producer waits between 0 and 5 seconds, then produces (increments) the semaphore value. The consumer should wait if the semaphore is at 0 until the producer frees up the resources.
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
sem_t my_semaphore;
pthread_mutex_t count_mutex;
void * consumerUse(void * ptr);
void * producerUse(void * ptr);
int main() {
int value;
pthread_t consumer, producer;
int valConsumer =0;
int valProducer =0;
sem_init(&my_semaphore, 0, 4);
sem_getvalue(&my_semaphore, &value);
printf("The initial value of the semaphore is %d\n", value);
for(int i=0; i < 100; i++)
{
valConsumer = pthread_create(& consumer, NULL, consumerUse, (void*)(intptr_t) value);
if(valConsumer != 0)
{
fprintf(stderr, "Error - pthread create () return code: %d\n", valConsumer);
exit(EXIT_FAILURE);
}
valProducer = pthread_create(& producer, NULL, producerUse, (void*) (intptr_t)value);
if(valProducer != 0)
{
fprintf(stderr, "Error - pthread create () return code: %d\n", valProducer);
exit(EXIT_FAILURE);
}
}
pthread_join( consumer, NULL);
pthread_join( producer, NULL);
printf("End program\n");
return 0;
}
void *consumerUse(void * ptr)
{
sleep(1);
int value;
sem_getvalue(&my_semaphore, &value);
printf("Before wait: %d\n", value);
pthread_mutex_lock(&count_mutex);
sem_wait(&my_semaphore);
pthread_mutex_unlock(&count_mutex);
sem_getvalue(&my_semaphore, &value);
printf("Consumer semaphore value: %d\n", value);
return 0;
}
void *producerUse(void * ptr)
{
int pause = rand() % 5;
sleep(pause);
int value;
sem_getvalue(&my_semaphore, &value);
printf("Before post: %d\n", value);
if(value < 4)
{
sem_post(&my_semaphore);
sem_getvalue(&my_semaphore, &value);
printf("Producer semaphore value: %d\n", value);
}
return 0;
}