Message Queues
Exchange prioritised messages and receive arrival notifications with POSIX message queues.
Overview
This sample walks through the POSIX message queue API:
a named queue is created with
mq_open()and persists untilmq_unlink(),messages are sent at different priorities with
mq_send()and received in descending priority order (FIFO among equal priorities) withmq_receive(), which also reports each message’s actual length and priority,mq_notify()registers aSIGEV_THREADnotification that runs a function in a new thread when a message arrives at the empty queue, demonstrating the classic re-register-then-drain idiom (a registration is consumed when it fires, and arrivals at a non-empty queue do not fire),mq_notify()then registers aSIGEV_SIGNALnotification, and the arrival signal - carrying the registered value, withsi_codeSI_MESGQ- is accepted synchronously withsigtimedwait(),mq_getattr()reports the queue geometry and fill level.
Building and Running
This project outputs to the console. It can be built and executed on QEMU as follows:
west build -b qemu_x86 samples/posix/message_passing
west run
Sample Output
received [prio 6]: urgent: fire drill
received [prio 3]: reminder: standup at 10
received [prio 3]: reminder: lunch at noon
received [prio 0]: newsletter
notified: 1 message(s) pending
drained [prio 1]: notify works
notified: 1 message(s) pending
drained [prio 1]: and re-arms, too
queue geometry: 8 x 48 bytes
done