Implement a blocking producer-consumer ring buffer (mutex + condition variable).
#include <pthread.h>
#include <stdint.h>
#define BQ_SIZE 16u
typedef struct {
uint8_t buf[BQ_SIZE];
unsigned head, tail, count;
pthread_mutex_t m;
pthread_cond_t not_empty, not_full;
} bqueue_t;
#define BQUEUE_INIT { .m = PTHREAD_MUTEX_INITIALIZER, \
.not_empty = PTHREAD_COND_INITIALIZER, .not_full = PTHREAD_COND_INITIALIZER }
void bq_put(bqueue_t *q, uint8_t v)
{
pthread_mutex_lock(&q->m);
while (q->count == BQ_SIZE) pthread_cond_wait(&q->not_full, &q->m);
q->buf[q->head] = v; q->head = (q->head + 1u) % BQ_SIZE; q->count++;
pthread_cond_signal(&q->not_empty);
pthread_mutex_unlock(&q->m);
}
uint8_t bq_get(bqueue_t *q)
{
pthread_mutex_lock(&q->m);
while (q->count == 0) pthread_cond_wait(&q->not_empty, &q->m);
uint8_t v = q->buf[q->tail]; q->tail = (q->tail + 1u) % BQ_SIZE; q->count--;
pthread_cond_signal(&q->not_full);
pthread_mutex_unlock(&q->m);
return v;
}
Points: wait in a while loop (spurious wake-ups, several consumers); the mutex protects all queue state; signal the other condition after changing the count. Works with many producers and consumers. Never call this from an ISR (it blocks): in an RTOS the equivalent is a message queue (xQueueSend / xQueueReceive), with FromISR variants for interrupts.