Xinhong Hu commented on a discussion: 
https://gitlab.rtems.org/rtems/rtos/rtems/-/issues/3791#note_142957


Hi @gedare ,

Thank you for your guidance. I've investigated how FreeBSD and Linux implement 
POSIX message queues regarding thread wake‑up order, and here's what I found:

**FreeBSD:**

FreeBSD **explicitly follows the POSIX specification**. Its `mq_receive` man 
page states:

> "If more than one thread is waiting to receive a message when a message 
> arrives at an empty queue and the Priority Scheduling option is supported, 
> then the **thread of highest priority that has been waiting the longest** 
> will be selected to receive the message."
>
> (Source: [FreeBSD 16.0-CURRENT man 
> page](https://man.freebsd.org/cgi/man.cgi?query=mq_receive&sektion=2&manpath=FreeBSD+16.0-CURRENT))

Internally, FreeBSD **does not maintain an explicit waiting thread queue**; 
instead, it uses a simple counter (`mq_receivers`) and relies on the kernel 
scheduler to select the appropriate thread when a message arrives. This design 
naturally yields the POSIX-mandated behavior.

**Linux:**

[Linux’s 
implementation](https://github.com/torvalds/linux/blob/master/ipc/mqueue.c) is 
more complex and **does not fully comply with the POSIX requirement**.

The waiting queue (`struct ext_wait_queue`) is a **linked list, but threads are 
inserted in priority order** (higher priority first). The insertion code 
(`wq_add` in `ipc/mqueue.c`) traverses the list and places a new thread 
**before the first thread with lower or equal priority**.

As a result, the list is sorted by descending priority, so when a message 
arrives, the **highest-priority thread** (the first in the list) is woken.

However, **within the same priority level, the insertion order is LIFO** (later 
waiters are placed ahead of earlier ones), so it does **not** guarantee that 
the longest-waiting thread is chosen.

\
This suggests that both FreeBSD and Linux prioritize threads by priority (Linux 
even within same priority uses LIFO rather than FIFO), aligning with the POSIX 
requirement to wake the highest priority thread. Linux's LIFO behavior for 
equal priorities may be a performance optimization but deviates from “longest 
waiting” part. 

Given these examples, I think RTEMS's current FIFO behavior for waiting threads 
is a deviation, and our proposal to add a priority-based discipline (either 
globally or per‑queue via \`mq_attr\`) would bring us closer to what other 
systems implement and what POSIX intends. 

I'd appreciate any further thoughts on this.

-- 
View it on GitLab: 
https://gitlab.rtems.org/rtems/rtos/rtems/-/issues/3791#note_142957
You're receiving this email because of your account on gitlab.rtems.org.


_______________________________________________
bugs mailing list
[email protected]
http://lists.rtems.org/mailman/listinfo/bugs

Reply via email to