ring-buffer/queue.h
/** Retrieves a message of at most *max* bytes from queue *q* and writes
 * it to *buffer*.
 *
 * Blocks until a message of no more than *max* bytes is available.
 *
 * Returns the number of bytes in the written message.
 */


Blocks until a message of no more than *max* bytes is available.

Returns the number of bytes in the written message.
Blocks until a message of no more than * max * bytes is available . Returns the number of bytes in the written message .
size_t queue_get(queue_t *q, uint8_t *buffer, size_t max)
{
    pthread_mutex_lock(&q->lock);
    message_t m;
    for (;;) {
        while ((q->tail - q->head) == 0)
            pthread_cond_wait(&q->readable, &q->lock);
        memcpy(&m, &q->buffer[q->head], sizeof(message_t));
        if (m.len > max) {
            while (q->head_seq == m.seq)
                pthread_cond_wait(&q->writeable, &q->lock);
            continue;
        }
        break;
    }
    memcpy(buffer, &q->buffer[q->head + sizeof(message_t)], m.len);
    q->head += m.len + sizeof(message_t);
    q->head_seq++;
    if (q->head >= q->size) {
        q->head -= q->size;
        q->tail -= q->size;
    }
    pthread_cond_signal(&q->writeable);
    pthread_mutex_unlock(&q->lock);
    return m.len;
}
size_t queue_get ( queue_t * q , uint8_t * buffer , size_t max ) { pthread_mutex_lock ( & q -> lock ) ; message_t m ; for ( ; ; ) { while ( ( q -> tail - q -> head ) == 0 ) pthread_cond_wait ( & q -> readable , & q -> lock ) ; memcpy ( & m , & q -> buffer [ q -> head ] , sizeof ( message_t ) ) ; if ( m . len > max ) { while ( q -> head_seq == m . seq ) pthread_cond_wait ( & q -> writeable , & q -> lock ) ; continue ; } break ; } memcpy ( buffer , & q -> buffer [ q -> head + sizeof ( message_t ) ] , m . len ) ; q -> head += m . len + sizeof ( message_t ) ; q -> head_seq ++ ; if ( q -> head >= q -> size ) { q -> head -= q -> size ; q -> tail -= q -> size ; } pthread_cond_signal ( & q -> writeable ) ; pthread_mutex_unlock ( & q -> lock ) ; return m . len ; }
Retrieves a message of at most *max* bytes from queue *q* and writes
 it to *buffer*.
Retrieves a message of at most * max * bytes from queue * q * and writes it to * buffer * .
// Wait for a message that we can successfully consume to reach the front of // the queue // Wait for a message to arrive // Read message header // Message too long, wait for someone else to consume it // We successfully consumed the header of a suitable message, so proceed // Read message body // Consume the message by incrementing the read pointer // When read buffer moves into 2nd memory region, we can reset to the 1st // region