information
The messaging mechanism is built directly into the tasks in pyRTOS. Each task has its own incoming and outgoing mailboxes. When a running task yields, a message is delivered. This messaging system is fairly simple. Each message has a sender and a recipient, and the message also has a type, which can be pyRTOS.QUIT or a user-defined type (see sample.py). User-defined types start with integer values 128 or higher. Types below 128 are reserved for future use by the pyRTOS API. Messages can contain a message field, but this is not required. If the type field is sufficient to pass the necessary information, it is best to leave the message field empty to save memory. The message field can contain anything, including objects and lists. If you need to pass parameters to a new task, one way to do this is to call deliver() on the newly created task object with a list or tuple of parameters. This will add the parameters to the task's message queue, allowing it to access the parameters during initialization.
Checking for messages is a critical part of any task that might receive messages. An unchecked message queue can accumulate so many messages that the system runs out of memory. If your task might receive messages, it is important to check for messages in every loop. Also be careful not to send too many messages to a low priority task without periodically blocking a higher priority task to give it time to process the message queue. If a task that receives messages never gets CPU time, this will lead to memory exhaustion.
Messages can be addressed by referencing the target task object or the name of the object. Names can be any type of comparable data, with numbers being the most efficient and strings being the most readable. Object reference addressing must be to an actual existing object, otherwise the operating system will crash. Also note that retaining references to terminated tasks will prevent those tasks from being garbage collected, creating potential memory leaks. Object references are the fastest method of message addressing, and they may provide some benefits when debugging, but it depends on how the user understands and avoids the associated hazards. Name addressing is much safer, however, messages sent to non-existent task names will be delivered silently, making some bugs harder to find. In addition, because name addresses require looking up the associated object, name-addressed messages will consume a lot of CPU time to deliver.
Several messaging examples are shown in sample.py.
|