Message Queues Internals
As previously described, a message consists of a pointer to actual data, a variable indicating the size of the data being pointed to and a timestamp indicating when the message was actually sent. When sent, a message is placed in a data structure of type OS_MSG
, shown in the figure below.
The sender and receiver are unaware of this data structure since everything is hidden through the APIs provided by µC/OS-III.
µC/OS-III maintains a pool of free OS_MSGs
. The total number of available messages in the pool is determined by the value of OS_CFG_MSG_POOL_SIZE
found in os_cfg_app.h
. When µC/OS-III is initialized, OS_MSGs
are linked in a single linked list as shown in the figure below. Notice that the free list is maintained by a data structure of type OS_MSG_POOL
, which contains four (4) fields: .NextPtr
, which points to the free list; .NbrFree
, which contains the number of free OS_MSGs
in the pool, .NbrUsed
, which contains the number of OS_MSGs
allocated to the application and, .NbrUsedMax
which detects the maximum number of messages allocated to the application.
Messages are queued using a data structure of type OS_MSG_Q
, as shown in the figure below.
.InPtr
This field contains a pointer to where the next OS_MSG
will be inserted in the queue. In fact, the OS_MSG
will be inserted “after” the OS_MSG
pointed to.
.OutPtr
This field contains a pointer to where the next OS_MSG
will be extracted.
.NbrEntriesSize
This field contains the maximum number of OS_MSGs
that the queue will hold. If an application attempts to send a message and the .NbrEntries
matches this value, the queue is considered to be full and the OS_MSG
will not be inserted.
.NbrEntries
This field contains the current number of OS_MSGs
in the queue.
.NbrEntriesMax
This field contains the highest number of OS_MSGs
existing in the queue at any given time.
A number of internal functions are used by µC/OS-III to manipulate the free list and messages. Specifically, OS_MsgQPut()
inserts an OS_MSG
in an OS_MSG_Q
, OS_MsgQGet()
extracts an OS_MSG
from an OS_MSG_Q
, and OS_MsgQFreeAll()
returns all OS_MSGs
in an OS_MSG_Q
to the pool of free OS_MSGs
. There are other OS_MsgQ??()
functions in os_msg.c
that are used during initialization.
The figure below shows an example of an OS_MSG_Q
when four OS_MSGs
are inserted.
OS_MSG_Qs
are used inside two additional data structures: OS_Q
and OS_TCB
. Recall that an OS_Q
is declared when creating a message queue object. An OS_TCB
is a task control block and, as previously mentioned, each OS_TCB
can have its own message queue when the configuration constant OS_CFG_TASK_Q_EN
is set to DEF_ENABLED
in os_cfg.h
. The figure below shows the contents of an OS_Q
and partial contents of an OS_TCB
containing an OS_MSG_Q
. The OS_MSG_Q
data structure is shown as an “exploded view” to emphasize the structure within the structure.