Task Priority and Preemption
Task priority informs the operating system of the importance of the task and the order in which a group of waiting tasks needs to execute. By setting the priorities of the tasks in the Task Manager block, tasks that need to react to critical or time-sensitive events can preempt lower priority and background tasks.
Tasks listed in the Task Manager block execute in a rate monotonic order. Rate-monotonic order requires the task with the highest static priority in the preempted state to immediately preempt all other tasks and enter the running state. Timer-driven tasks with shorter periods get higher static priorities. If two tasks with equal priority in the preempted state, when no other running task exists, then tasks execute in a first-in, first-out (FIFO) order.
Each event-driven task listed in the Task Manager block can be set with an explicit execution priority. Timer-driven tasks inherit their priority from the base rate task priority of the model. In the configuration parameters, the base rate task priority is set by the Hardware Implementation > Hardware board settings > Operating system/scheduler > Base rate task priority parameter. The following example shows the interaction between a pair of competing tasks.
Preemption of Low Priority Task by High Priority Task
This example shows how the task manager changes the state of two tasks, preempting the lower priority task to allow the high priority task to run.
Task Manager with High and Low Priority Tasks
The following model simulates a software application with a high and low priority task. A Task Manager block schedules the execution of the task subsystems inside the Software Application Model Reference block.
The low priority, timer driven, task is scheduled to run every 0.5 seconds with a duration of 0.2 seconds. The high priority, event driven, task is scheduled to run when a new UDP data packet arrives, which occurs every 1.1 seconds and requires a task duration of 0.5 seconds. As a result of these timing conditions, the low priority task gets preempted to allow the high priority task to run.
Simulation Showing Task Preemption
Click the Run button to build and run the model. When the model finishes running, open the Simulation Data Inspector to see the results of the simulation. Select the HighPriority and LowPriority task waveforms to see the task preemption.
Inspecting the Simulation Data Inspector at time 1.0, the low priority task starts executing until time 1.1, getting preempted by high priority task. The low priority task then runs to completion at 1.7 seconds, overrunning the next instance of the low priority task that should have started at 1.5 seconds.