pthread condition variables
I am creating a ringbuffer that supports multithreaded calls from both consumers and producers, and, while I feel fairly confident that the code looks right, when I run it I find (with a debugging trace statement) that it is actually running gets when the buffer is empty, or puts when the buffer is full. Please look over the pthread condition variables and let me know if you see something wrong.
Code:
void
ringbuf_put(ringbuf_t *rb,value_type y)
{
pid=pthread_self();
pthread_mutex_lock(&mtx);
while (rb->size>=rb->capacity)
{
pthread_cond_wait(¬_full, &mtx);
rb->buf[rb->tail]=y;
if (rb->tail==rb->capacity)
rb->tail=0;
rb->tail++;
rb->size++;
//printf("PUT, %d, %d, %d, %d, %d, Inside condition\n", pid, cid, rb->size, rb->capacity, y);
if (rb->size>10)
{pthread_cond_signal(¬_empty);}
pthread_mutex_unlock(&mtx);
return;
}
if (rb->size<rb->capacity)
{
rb->buf[rb->tail]=y;
if (rb->tail==rb->capacity)
rb->tail=0;
rb->tail++;
rb->size++;
//printf("PUT, %d, %d, %d, %d, %d\n", pid, cid, rb->size, rb->capacity, y);
if (rb->size>10)
{pthread_cond_signal(¬_empty);}
pthread_mutex_unlock(&mtx);
return;
}
printf("failed PUT call\n");
}
value_type
ringbuf_get(ringbuf_t *rb)
{
value_type x;
cid=pthread_self();
pthread_mutex_lock(&mtx);
while (rb->size <= 0)
{
pthread_cond_wait(¬_empty, &mtx);
x = rb->buf[rb->head];
if (rb->head==rb->capacity)
rb->head=0;
else
rb->head++;
rb->size--;
// printf("GET, %d, %d, %d, %d, %d, Inside condition\n", pid, cid, rb->size, rb->capacity, rb->buf[rb->head]);
if (rb->size<(rb->capacity-10))
{pthread_cond_signal(¬_full);}
pthread_mutex_unlock(&mtx);
return x;
}
if (rb->size > 0)
{
x = rb->buf[rb->head];
if (rb->head==rb->capacity)
rb->head=0;
else
rb->head++;
rb->size--;
// printf("GET, %d, %d, %d, %d, %d\n", pid, cid, rb->size, rb->capacity, rb->buf[rb->head]);
if (rb->size<(rb->capacity-10))
{pthread_cond_signal(¬_full);}
pthread_mutex_unlock(&mtx);
return x;}
printf("failed GET call\n");
}