I recently learned Semaphore and Consumer Producer problem in class and encountered this question: I used two semaphores to indicate the empty and the full in a buffer plus a mutex.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
pthread_mutex_t mutex;
sem_t empty;
sem_t full;
int fill =0 ;
void *producer(void *param);
void *consumer(void *param);
void* producer(void *param)
{
while(1) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
fill++;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *param)
{
while(1){
sem_wait(&full);
pthread_mutex_lock(&mutex);
fill--;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void* dynamic_output(void* ptr){
while(1){
printf("fill = :%d\n",fill);
sleep(1);
}}
int main()
{
pthread_mutex_init(&mutex, NULL);
sem_init(&empty, 0, 5);
sem_init(&full, 0, 0);
pthread_t gid1,oid1;
pthread_t dy;
pthread_create(&dy,NULL,dynamic_output,NULL);
pthread_create(&gid1,NULL,&producer,NULL);
pthread_create(&oid1,NULL,&consumer,NULL);
pthread_join(gid1,NULL);
pthread_join(oid1,NULL);
return 0;
}
here I simply put a variable named 'fill' inside the producer and the consumer. Since I initiated the empty semaphore to 5, I expected 'fill' will be floating between 0 - 5 but when I printed them out I found the weird result:
fill = :0
fill = :19
fill = :446
fill = :112
fill = :156
fill = :-564
fill = :-345
fill = :-744
fill = :-1293
I really don't understand how fill could've become a negative number or number bigger than 5. I thought implementing the semaphores could ensure that the bounded buffer( here I didn't really have a buffer).
Thanks in advance.