Many systems choose the message-driven system scheduling model during design. Such a model is widely used in the software design of switches and many communication products. For small embedded applications without operating systems, such a model is very vital.
The scheduling system can be divided into several modules. According to the actual needs of the system, you can set several modules and define the types of messages sent to each module. All messages have the same header.
Struct msg_hdr_t {
Int moduleid;/* ID of the module to which the message is sent */
Int MSG;/* Message Type */
Int Len;/* message length */
Struct msg_hdr_t * Next;/* points to the next message in the message queue */
};
The message-driven system can be divided into three parts: 1. Send messages; 2. receive messages; 3. Schedule messages. All messages are placed in a message queue. The priority of the module is determined based on the order of the registered message processing function.
When sending a message, you first need to allocate the message. In the embedded system, you can use a fixed message length based on the actual situation, which can simplify the memory allocation. Generally, when a system is running, messages that are not processed can be computed, so the size of the memory to be allocated can be calculated.
Void * msg_allocate (INT Len)/* The input parameter is the length of the message body, and the return address is the first address of the message body */
{
Struct msg_hdr_t * HDR;
If (LEN <= 0 ){
Return NULL;
}
HDR = (struct msg_hdr_t *) mem_alloc (LEN + sizeof (struct msg_hdr_t ));
If (HDR ){
HDR-> Len = Len;
HDR-> next = NULL;
HDR-> moduleid = module_id_invalid;
Return (void *) (HDR + 1 ));
}
Return NULL;
}
You can replace mem_alloc with your own implementations to specify your own memory allocation method.
Int msg_send (INT module, void * msg_ptr)
{
/* Sanity check */
If (msg_ptr = NULL | false = msg_valid_module (module )){
Msg_deletion (msg_ptr );
Return error_invalid_parameter;
}
If (msg_next (msg_ptr )! = NULL | msg_module_id (msg_ptr )! = Module_id_invalid ){
Msg_deletion (msg_ptr );
Return error_invalid_parameter;
}
Msg_module_id (msg_ptr) = module;
Msg_enqueue (msg_ptr );
Msg_set_event (module, have_msg_flags );
}
The parameters of the message sending function are the ID of the module to be sent and the message body. In each message processing function, msg_deletion is called to release the received message.
The operations on the message header are completed using the following four macros:
Msg_module_id: gets the ID of the module to which the message is sent.
Msg_len: Message Body Length
Msg_nex: Next message
Msg_msg: Message Type
The specific implementation can be downloaded from the source code.