Reputation: 29
here im trying to, use a circular queish thing for my insert and remove methods, as well as use the insert and remove functions for synchronization im compiling with gcc file.c -lpthread -lrt and running with ./a.out 50 1 1.
upon running my producer produces and outputs correctly
producer thread #0
consumer thread #0
producer produced 7
but for whatever reason i cannot get my consumer to output,
i have tried putting my return 0; for each functions outside the locks and semaphores and it does indeed output consumer, but too many times when it should only run once per thread,
its also using a standard counting semaphore 2 of them as well as a single mutex lock
this is what happens when i move the return below the locks
producer thread #0
consumer thread #0
producer produced 7
consumer consumed 7
producer produced 5
producer produced 5
consumer consumed 5
consumer consumed 2
producer produced 7
producer produced 4
consumer consumed 7
consumer consumed 4
producer produced 6
consumer consumed 6
producer produced 1
consumer consumed 1
producer produced 9
consumer consumed 9
producer produced 2
consumer consumed 2
producer produced 6
consumer consumed 6
when in reality there should if i run ./a.out 50 1 1 there should only be one producer and one consumer
update: working on a new version on this so taking back my previous code, will post new version
Upvotes: 0
Views: 125
Reputation: 75062
In the functions insert_item()
and remove_item()
, returning (end of execution of the functions) happens before executing pthread_mutex_unlock()
. This will prevent them from unlocking and prevent 2nd or later execution of the functions.
Instead of this, you should store the value to return in a variable and return that after unlocking. This can be done like this:
int insert_item(buffer_item item)
{
int ret;
sem_wait(&empty);
pthread_mutex_lock(&lock);
if (size_check < BUFFER_SIZE)
{
buffer[insertBounds_check++] = item;
size_check++;
ret = 0;
}
else
{
ret = -1;
}
pthread_mutex_unlock(&lock);
sem_post(&full);
return ret;
}
Upvotes: 2