Task
Task
Task
2
FreeRTOS
3
The simplest case of task priority
assignments
• Assign higher priorities (lower priorities) to
threads that implement hard real-time (soft real-
time) requirements
– As a result, hard real-time threads are always
executed ahead of soft real-time threads.
• But, priority assignment decision are not always
that simple.
4
A note about terminology
5
Why use a real-time kernel
• For a simple system, many well-established
techniques can provide an appropriate solution
without the use of a kernel.
• For a more complex embedded application, a
kernel would be preferable.
• But where the crossover point occurs will always
be subjective.
6
Benefits of using real-time kernel 1
• Abstracting away timing information
– Kernel is responsible for execution timing and provides a time-related
API to the application. This allows the application code to be simpler
and the overall code size be smaller.
• Maintainability/Extensibility
– Abstracting away timing details results in fewer interdependencies
between modules and allows sw to evolve in a predictable way.
– Application performance is less susceptible to changes in the underlying
hardware.
• Modularity
– Tasks are independent modules, each of which has a well-defined
purpose.
• Team development
– Tasks have well-defined interfaces, allowing easier development by
teams
7
Benefits of using real-time kernel 2
• Easier testing
– Tasks are independent modules with clean interfaces, they
can be tested in isolation.
• Idle time utilization
– The idle task is created automatically when the kernel is
started. It executes whenever there are no application
tasks to run.
– Be used to measure spare processing capacity, perform
background checks, or simply place the process into a
low-power mode.
• Flexible interrupt handling
– Interrupt handlers can be kept very short by deferring most
of the required processing to handler tasks.
8
Standard FreeRTOS features
9
Outline
• Task Management
• Queue Management
• Interrupt Management
• Resource Management
• Memory Management
• Trouble Shooting
10
TASK MANAGEMENT
11
Introduction and scope
12
More specific topics
14
ATaskFunction
15
Special features of task function
• FreeRTOS task
– Must not contain a ‘return’ statement
– Must not be allowed to execute past the end of
the function
– If a task is no longer required, it should be
explicitly deleted.
– Be used to create any number of tasks
• Each created task is a separate execution instance with
its own stack, and its own copy of any automatic
variables defined within the task itself.
16
Top level task states
18
All parameters
• pvTaskCode
– a pointer to the function (just the function name)
that implements the task.
• pcName
– A descriptive name for the task. It is not used by
FreeRTOS, but a debugging aid.
– configMAX_TASK_NAME_LEN: the application
defined constant that defines the maximum length a
task name can task including the NULL terminator.
19
• uxStackDepth
– Each task has its own unique stack that is
allocated by the kernel to the task when the task
is created.
– The value specifies the number of words the task
stack can hold.
• E.g., Cortex-M3 stack is 32 bits wide, if usStackDepth
is passed in as 100, 400 bytes of stack space will be
allocated (100*4 bytes)
– Size of the stack used by the idle task is defined
by configMINIMAL_STACK_SIZE.
• Adjustable w.r.t. applications
20
• pvParameters
– The value assigned to pvParameters will be the
values passed into the task.
• uxPriority
– defines the priority at which the task will execute.
– Priorities can be assigned from 0, which is the
lowest priority, to (configMAX_PRIOIRTIES-1),
which is the highest priority.
– Passing a value above (configMAX_PRIOIRTIES -
1) will result in the priority being capped the
maximum legitimate value.
21
• pxCreatedTask
– pass out a handle to the created task, then be used to
refer the created task in API calls.
• E.g., change the task priority or delete the task
– Be set to NULL if no use for the task handle
22
Example 1 Creating 2 tasks
23
vTask1
void vTask1( void *pvParameters )
{
const char *pcTaskName = "Task 1 is running\r\n";
volatile unsigned long ul;
}
26
example001 - Serial Monitor
27
Execution pattern of two Example 1 tasks
29
Example 2 vTaskFunction
void vTaskFunction( void *pvParameters )
{
char *pcTaskName;
volatile unsigned long ul;
/* The string to print out is passed in via the parameter. Cast this to a
character pointer. */
pcTaskName = ( char * ) pvParameters;
for( ;; );
}
31
example002 - Serial Monitor
32
1.5 Task priorities
• configMAX_PRIORITIES in FreeRTOSConfig.h
– Maximum number of priorities
– Higher this value, more RAM consumed
Range: [0(low), configMAX-PRIORITIES-1(high)]
– Any number of tasks can share the same priority
33
• To select the next task to run, the scheduler itself
must execute at the end of each time slice.
– Use a periodic interrupt called the tick (interrupt).
– Effectively set the length of time slice by the tick
interrupt frequency -- configTICK_RATE_HZ in
FreeRTOSConfig.h
• configTICK_RATE_HZ
– If it is 100(Hz), the time slice will be 10 ms.
– API always calls specify time in tick interrupts (ticks)
• portTICK_PERIOD_MS
– Convert time delays from milliseconds into the
number of tick interrupts.
34
• When kernel itself is running, the arrows in the
above figure show the sequence of execution
from task interrupt, then from interrupt back to a
next task.
35
Example 3. Experimenting with priorities
36
Example 3. Experimenting with priorities
37
example003 - Serial Monitor
38
• The scheduler always selects the highest priority
task that is able to run.
– Task 2 has a higher priority than Task 1; so Task 2 is
the only task to ever enter the Running state.
– Task 1 is to be ‘starved’ of processing time of Task 2.
39
‘Continuous processing’ task
• An event-driven task
– has work to perform only after the occurrence of the event
that triggers it
– Is not able enter the Running state before that event has
occurred.
• The scheduler selects the highest priority task that is
able to run.
– High priority tasks not being able to run means that the
scheduler cannot select them, and
– Must select a lower priority task that is able to run.
• Using event-driven tasks means that
– tasks can be created at different priorities without the
highest priority tasks starving all the lower priority tasks.
41
Full task state machine
42
Blocked state
43
Suspended state
44
Ready state
45
Full Task State machine
46
Example004 - Using the Block state to
create a delay
• All tasks in the previous examples have been
periodic
– They have delayed for a period and printed out
their string before delay once more, and so on.
– Delayed generated using a null loop
• the task effectively polled an incrementing loop counter
until it reached a fixed value.
47
• Disadvantages to any form of polling
– While executing the null loop, the task remains in
the Ready state, ‘starving’ the other task of any
processing time.
– During polling, the task does not really have any
work to do, but it still uses maximum processing
time and so wastes processor cycles.
• This example corrects this behavior by
– replacing the polling null loop with a call to
vTaskDelay() API function.
– setting INCLUDE_vTaskDelay to 1 in
FreeRTOSConfig.h
48
vTaskDelay() API function
51
• Each time the tasks leave the Blocked state they
execute for a fraction of a tick period before re-
entering the Blocked state.
– Most of the time no application tasks are able to run and,
so, no tasks can be selected to enter the Running state.
– The idle task will run to ensure there is always at least one
task that is able to run. 52
Bold lines indicate the state transitions
performed by the tasks in Example 4
53
vTaskDelayUntil() API Function
• Parameters to vTaskDelayUntil()
– specify the exact tick count value at which the
calling task should be moved from the Blocked
state into the Ready state.
– Be used when a fixed execution period is
required.
• The time at which the calling task is unblocked is
absolute, rather than relative to when the function was
called (as vTaskDelay())
void vTaskDelayUntil( TickType_t
*pxPreviousWakeTime, const TickType_t
xTimeIncrement );
54
vTaskDelayUntil() prototype
• pxPreviousWakeTime
– Assume that vTaskDelayUtil() is being used to
implement a task that executes periodically and
with a fixed frequency.
– Holds the time at which the task left the Blocked
state.
– Be used as a reference point to compute the time
at which the task next leaves the Blocked state.
– The variable pointed by pxPreviousWakeTime is
updated automatically, not be modified by
application code, other than when the variable is
first initialized.
55
vTaskDelayUntil() prototype
• xTimeIncrement
– Assume that vTaskDelayUtil() is being used to
implement a task that executes periodically and
with a fixed frequency – set by xTimeIncrement.
– Be specified in ‘ticks’. The constant
portTICK_PERIOD_MS can be used to convert
ms to ticks.
56
Example 5 Converting the example tasks
to use vTaskDelayUntil()
• Two tasks created in Example 4 are periodic
tasks.
• vTaskDelay() does not ensure that the
frequency at which they run is fixed,
– as the time at which the tasks leave the Blocked
state is relative to when they call vTaskDelay().
57
• In void vTaskFunction(void *pvParameters)
Change
vTaskDelay(250 / portTICK_RATE_MS);
// a period of 250ms is being specified.
To
vTaskDelayUntil( &xLastWakeTime, (250 /
portTICK_PERIOD_MS));
/*xLastWakeTime is initialized with the current tick count
before entering the infinite loop. This is the only time it is
written to explicitly. */
xLastWakeTime = xTaskGetTickCount();
/*It is then updated within vTaskDelayUntil();
automatically */
58
Example 5 - Serial Monitor
59
Example 6 Combining blocking and non-
blocking tasks
• Two tasks are created at priority 1.
– Always be either the Ready or the Running state
as never making any API function calls.
– Tasks of this nature are called continuous
processing tasks they always have work to do.
• A Third task is created at priority 2.
– Periodically prints out a string by using
vTaskDelayUntil() to place itself into the Blocked
state between each print iteration.
60
void vContinuousProcessingTask(void * pvParameters) {
char *pcTaskName;
pcTaskName = (char *) pvParameters;
for (;;) { Serial.print(pcTaskName);
delay(100);
}}
62
63
Idle Task and the Idle task hook
• The idle task is created automatically when the
RTOS scheduler is started to ensure there is
always at least one task that is able to run.
• It is created at the lowest possible priority to
ensure it does not use any CPU time if there are
higher priority application tasks in the
ready state.
• The idle task is responsible for freeing
memory allocated by the RTOS to tasks that have
since been deleted. It is therefore important in
applications that make use of
the vTaskDelete() function to ensure the idle task
is not starved of processing time. 64
• The Idle task is immediately swapped out to
allow Task 2 to execute at the instant Task 2
leaves the Blocked state.
– Task 2 pre-empts the idle task automatically.
65
Idle Task Hook Functions
68
Change the priority of a task
70
Example 8 Changing task priorities
71
Expected Behavior of Example 8
73
• Change vTask1 by initialization
unsigned portBASE_TYPE uxPriority;
uxPriority = uxTaskPriorityGet(NULL);
• And adding to the infinite loop
vTaskPrioritySet(xTask2Handle,
(uxPriority+1));
75
Task execution sequence
76
Deleting a task
• Function prototype
void vTaskDelete( TaskHandle_t xTask );
78
Example 9
for( ;; );
79
void vTask1( void *pvParameters )
{
const TickType_t xDelay100ms = 100 / portTICK_PERIOD_MS;
for( ;; )
{
/* Print out the name of this task. */
Serial.print( "Task1 is running\r\n" );
/* Task2 has/had the higher priority, so for Task1 to reach here Task2
must have already executed and deleted itself. Delay for 100
milliseconds. */
vTaskDelay( xDelay100ms );
}
}
80
void vTask2( void *pvParameters )
{
/* Task2 does nothing but delete itself. To do this it
could call vTaskDelete() using a NULL parameter, but
instead and purely for demonstration purposes it
instead calls vTaskDelete() with its own task handle. */
Serial.print( "Task2 is running and about to delete
itself\r\n" );
vTaskDelete( xTask2Handle );
}
Example 9 - Serial Monitor
81
Example 9 Deleting tasks (Behavior)
1. Task 1 is created by setup() with priority 1. When it runs,
it creates Task 2 at priority 2. Task 2 as the highest priority
task starts to execute immediately.
2. Task 2 does nothing but delete itself by passing NULL or its
own task handle.
3. When Task 2 has been deleted, Task 1 is again the highest
priority task, so continues executing – at which point it calls
vTaskDelay() to block for a short period.
4. The idle task executes while Task 1 is in the blocked state
and frees the memory that was allocated to the now deleted
Task 2.
5. When Task 1 leaves the blocked state it again becomes the
highest priority Ready state task and preempts the Idle task.
Then, start from Step1 again.
82
Execution sequence
83
Scheduling Algorithms - Summary
84
Selecting the Scheduling Algorithm
The scheduling algorithm is the software routine that decides which Ready state task to
transition into the Running state. All the examples so far have used the same scheduling
algorithm, but the algorithm can be changed using
the configUSE_PREEMPTION and configUSE_TIME_SLICING configuration constants. Both
constants are defined in FreeRTOSConfig.h.
• Time Slicing: Time slicing is used to share processing time between tasks
of equal priority, even when the tasks do not explicitly yield or enter
the Blocked state. Scheduling algorithms described as using Time
Slicing select a new task to enter the Running state at the end of each
time slice if there are other Ready state tasks that have the same priority
as the Running task. A time slice is equal to the time between two RTOS
tick interrupts.
85
Tasks in the Blocked state
• Tasks can wait in the Blocked state for an event
and are automatically moved back to the Ready
state when the event occurs.
• Temporal events
– Occur at a particular time, e.g. a block time expires.
– Generally be used to implement periodic or timeout
behavior.
• Synchronization events
– Occur when a task or ISR sends info to a queue or to
one of the many types of semaphore.
– Generally be used to signal asynchronous activity,
such as data arriving at a peripheral.
86
Execution pattern highlighting task prioritization and preemption in a hypothetical
application in which each task has been assigned a unique priority
88
• Task 3
– An event-driven task
• Execute with a low priority, but above the Idle task priority.
– It spends most of its time in the Blocked state waiting
for the event of interest, transitioning from Blocked to
Ready state each time the event occurs.
• All FreeRTOS inter-task communication mechanisms (task
notifications, queues, semaphores, etc.) can be used to signal
events and unblock tasks in this way.
– Event occur at t3, t5, and also between t9 and t12.
• The events occurring at t3 and t5 are processed immediately
as it is the highest priority task that is able to run.
• The event occurring somewhere between t9 and t12 is not
processed as until t12 because, until then, the higher priority
tasks Task 1 and Task 2 are still executing. It is only at time
t12 that both Task 1 and Task 2 are in the Blocked state,
89
making Task 3 the highest priority Ready state task.
• Task 2
– A periodic task that executes at a priority above
Task 3, but below Task1. The period interval
means Task 2 wants to execute at t1, t6 and t9.
• At t6, Task 3 is in Running state, but task 2 has the
higher relative priority so preempts Task 3 and start to
run immediately.
• At t7, Task 2 completes its processing and reenters the
Blocked state, at which point Task 3 can re-enter the
Running state to complete its processing.
• At t8, Task 3 blocks itself.
90
• Task 1
– Also an event-driven task.
– Execute with the highest priority of all, so can preempt any
other task in the system.
– The only Task 1 event shown occurs at t10, at which time
Task 1 pre-empts Task 2.
– Only after Task 1 has re-entered the Blocked at t11, Task 2
can complete its processing.
91
Execution pattern highlighting task
prioritization and time slicing in a hypothetical
application in which two tasks run at the same
priority
• The Idle Task and Task 2
The Idle task and Task 2 are both continuous processing tasks, and both have a priority
of 0 (the lowest possible priority). The scheduler only allocates processing time to the
priority 0 tasks when there are no higher priority tasks that are able to run, and shares
the time that is allocated to the priority 0 tasks by time slicing. A new time slice starts
on each tick interrupt, which occurs at times t1, t2, t3, t4, t5, t8, t9, t10 and t11.
The Idle task and Task 2 enter the Running state in turn, which can result in both tasks
being in the Running state for part of the same time slice, as happens between time t5
and time t8.
• Task 1
The priority of Task 1 is higher than the Idle priority. Task 1 is an event driven task
that spends most of its time in the Blocked state waiting for its event of interest,
transitioning from the Blocked state to the Ready state each time the event occurs.
The event of interest occurs at time t6. At t6 Task 1 becomes the highest priority
task that is able to run, and therefore Task 1 preempts the Idle task part way
through a time slice. Processing of the event completes at time t7, at which point
Task 1 re-enters the Blocked state.
The configIDLE_SHOULD_YIELD compile time configuration constant can be used to
change how the Idle task is scheduled:
•If configIDLE_SHOULD_YIELD is set to 0 then the Idle task remains in
the Running state for the entirety of its time slice, unless it is preempted by a higher
priority task.
•If configIDLE_SHOULD_YIELD is set to 1 then the Idle task yields (voluntarily gives up
whatever remains of its allocated time slice) on each iteration of its loop if there are other
Idle priority tasks in the Ready state.
Prioritized Preemptive Scheduling without Time Slicing
If time slicing is not used, then the scheduler only selects a new task to enter
the Running state when either:
• A higher priority task enters the Ready state.
• The task in the Running state enters the Blocked or Suspended state.
There are fewer task context switches when time slicing is not used than when time
slicing is used. Therefore, turning time slicing off results in a reduction in the scheduler's
processing overhead. However, turning time slicing off can also result in tasks of equal
priority receiving greatly different amounts of processing time, a scenario
demonstrated by Figure above. For this reason, running the scheduler without time
slicing is considered an advanced technique that should only be used by experienced
users.
Co-operative scheduling
• When using the cooperative scheduler, a context
switch occur only when
– the Running state task enters the Blocked state
or
– the Running state task explicitly calls
taskYIELD() – a Kernel Control API function.
• Tasks will never be pre-empted and tasks of equal
priority will not automatically share processing
time (time slicing cannot be used).
– Results in a less responsive system.
94
Co-operative scheduling
Figure below demonstrates the behavior of the cooperative scheduler.
The horizontal dashed lines in the figure show when a task is in the Ready state.