A tiny header-only, thread-safe queue for Linux/POSIX using pthread_mutex_t and pthread_cond_t.
The API is intentionally modeled after a minimal subset of the FreeRTOS Queue functions.
This repo includes:
queue.h: the queue implementation (ring buffer + pthread sync)main.c: a simple producer/consumer demo
- Fixed-size ring buffer (FIFO)
- By-value item storage (
item_sizebytes per item) - Multiple producers / multiple consumers (protected by a single mutex)
- Blocking / timed blocking semantics similar to FreeRTOS:
0ticks: do not waitportMAX_DELAY: wait forever- otherwise: wait up to
xTicksToWaitticks
- Extra API: send to front (priority push)
gcc -Wall -Wextra -O2 -pthread main.c -o queue_demo
./queue_demoYou should see the producer sending numbers and the consumer receiving them (consumer is slower so the queue can become full).
Include the header:
#include "queue.h"Create a queue:
QueueHandle_t q = xQueueCreate(QUEUE_LEN, sizeof(int));Send / Receive:
int v = 123;
xQueueSend(q, &v, 100); // wait up to 100 ticks if full
int out = 0;
xQueueReceive(q, &out, portMAX_DELAY); // wait forever until an item arrivesDelete when done:
vQueueDelete(q);Creates a queue able to store uxQueueLength items, each uxItemSize bytes.
Returns NULL on allocation/init failure.
Pushes an item to the back of the queue (FIFO).
Returns:
pdTRUEon successpdFALSEon failure/timeout
BaseType_t xQueueSendToFront(QueueHandle_t xQueue, const void* pvItemToQueue, TickType_t xTicksToWait)
Pushes an item to the front of the queue (priority insert).
The next xQueueReceive() will return this item before older items.
Pops an item from the front of the queue into pvBuffer (must be at least item_size bytes).
Returns:
pdTRUEon successpdFALSEon failure/timeout
Destroys mutex/condition variables and frees the queue buffer + object.
Timeouts are expressed in ticks. The conversion is:
wait_ms = xTicksToWait * QUEUE_TICK_MS
You can override QUEUE_TICK_MS at compile time:
gcc -DQUEUE_TICK_MS=10 -pthread main.c -o queue_demoOr in a config header before including queue.h.
- Clock source:
pthread_cond_timedwait()usesCLOCK_REALTIMEby default, and this implementation builds deadlines usingCLOCK_REALTIME. If the system time jumps (NTP adjustment / manual clock change), the effective timeout may shift. - This queue stores items by value (copies bytes). If you store pointers, you manage the pointed memory lifetime yourself.
- Condition variables use
pthread_cond_signal()(wake one waiter). This is typically what you want for queue semantics.
No license file is included in this snippet. If you plan to publish/distribute, consider adding a license (MIT/BSD/Apache-2.0, etc.).