Skip to main content

Embedded Expertise

Task Priorities in FreeRTOS – Part 1: The Essential Three

Many FreeRTOS beginners grapple with a practical question: how many task priorities are “enough”? Documentation and tutorials often focus on technical details, leaving this crucial good-practice consideration unanswered. This series tackles this very question, guiding you from the essential minimum to strategic priority use.

A Message From Max

QuoteDear Embedded Experts –

I’m developing an embedded application using FreeRTOS and I’m currently defining task priorities. I’ve noticed a wide range in the number of priorities used in various examples and reference libraries. Some suggest 3-5 priorities, while others showcase applications with over 20.

I understand FreeRTOS itself doesn’t enforce a specific number, but I’m unsure about the best approach for my application. Considering factors like responsiveness, code complexity, and future maintainability, could you advise on how to determine a suitable number of task priorities for my project?

For reference, my application is basically a data pump: it reads from one protocol, extracts the payload, and forwards to another protocol. There are also a few ancillary tasks such as tracing and logging the operations.

Max, you’re absolutely right! Many developers, especially those new to FreeRTOS, find task priorities a bit of a head-scratcher. The good news is that you’re proactive in figuring out the right number for your application before diving in. That’s a good first step!

While we won’t be providing a specific recommendation for your data pump application just yet, this series will equip you with a framework of thought. We’ll explore best practices that help you balance responsiveness, code clarity, and future maintainability. This framework will guide you towards determining the ideal number of priorities for your specific needs – reading from one protocol, extracting data, and forwarding to another, with some logging on the side. Let’s dive in!

Short Answer For The Impatient

  • 3: A reasonable minimum
  • 5-6: Typical, perfect for most applications
  • 10+: A recipe for a maintenance disaster

 

Curious to know a bit more? Read on.

How Scheduler and Priorities Work Together

For this discussion, we assume a single-core system with preemption enabled (configUSE_PREEMPTION = 1).

FreeRTOS runs the highest-priority task that is ready to execute. A task waiting for a message, notification, semaphore, or timeout is blocked and does not compete for CPU time.

Scheduling decisions are not limited to tick interrupts:

  • When the running task blocks, the scheduler selects the highest-priority task that remains ready.

  • When a task operation unblocks a higher-priority task, that task can preempt the current one without waiting for the next tick.

  • When an interrupt unblocks a higher-priority task, the interrupt handler should request a context switch using the appropriate port macro, commonly portYIELD_FROM_ISR(). The task can then run as the processor leaves interrupt context.

The periodic tick maintains the kernel’s time base and allows tasks to unblock when their delays or timeouts expire. When time slicing is enabled (configUSE_TIME_SLICING = 1), it also makes ready tasks of equal priority take turns on successive ticks. Its frequency is configured through configTICK_RATE_HZ.

A task can explicitly request rescheduling with taskYIELD(). In normal preemptive operation, this lets another ready task of the same priority run. If none exists, the calling task continues.

Crucially, taskYIELD() does not let lower-priority tasks run while the calling task remains ready. To make CPU time available to them, a higher-priority task should normally block while waiting for work, rather than repeatedly poll or yield.

Task Trio: Classifying Tasks and Setting Priorities Effectively

Now that we understand how FreeRTOS uses task priorities, let’s revisit Max’s initial question: how many priorities do we actually need?

There isn’t a one-size-fits-all answer, but most applications can be categorized into three main task types based on their real-time requirements:

  1. Hard Real-Time Tasks: These tasks have strict deadlines that must be met under all circumstances. Missing a deadline could have critical consequences for your system’s functionality. Examples include timestamping an event or maintaining communication timeouts. These tasks typically require the highest priority in FreeRTOS to ensure they are preempted only bysystem events (interrupts, inc. the tick).

  2. Background Tasks: On the other end of the urgency spectrum, these lowest priority tasks can tolerate some delays without impacting functionality. They often handle background activities like housekeeping chores, power management or watchdog operations. The idle task provided by FreeRTOS falls into this category. It’s the lowest priority task that gets executed only when no other tasks are ready to run.

  3. Normal Application Tasks: All the rest: These tasks represent the bulk of your application logic and typically don’t have strict real-time constraints. They might handle user interface updates, data processing, communication protocols, or other application-specific functionalities. In many cases, these tasks can share a common mid-range priority. The FreeRTOS scheduler will ensure a fair share of CPU time for all tasks at this level, balancing responsiveness with efficient resource utilization.

There’s one thing that can’t be understated: By identifying a task as low urgency and assigning it a low priority, you actually improve the responsiveness of the rest of the system. Low priorities do matter!

By understanding these different task categories and their real-time requirements, we can start to define a suitable number of task priorities for your specific application. In the next section, we’ll explore different approaches to setting task priorities and avoiding common pitfalls.

From Theory to Code: Defining Task Priorities with C Macros

Based on the three task categories we have introduced before, let’s solidify our priority definitions with some concrete values. A convenient place to do so is in your FreeRTOSConfig.h file:

The last line defines the maximum number of priority levels that can be used within your FreeRTOS system. It’s probably already defined in your FreeRTOSConfig.h and should be adjusted there, i.e. not redefined. It’s important to consider that managing a large number of priorities can introduce overhead. The higher the number of  priorities, the longer the switching time. Additionally, a larger number of priorities might slightly increase memory usage.

The focus of this series is on using a minimal effective number of priorities for your specific application, rather than necessarily utilizing the entire configurable maximum. By following these guidelines, you can ensure efficient task management and a simple yet well-structured FreeRTOS system.

// Idle task has lowest priority  (0) and is already defined somewhere else
#define configPRIORITY_BACKGROUND (1) // Low priority tasks, lowest urgency
#define configPRIORITY_NORMAL (2) // Normal application tasks, mid-range prio
#define configPRIORITY_RT (3) // Hard real-time tasks, strictest deadlines
#define configMAX_PRIORITIES (4)

Remember, this is just a starting point. Purists may want to define the priorities in a more cryptic way with formulas like:

#define configPRIORITY_NORMAL (configMAX_PRIORITIES / 2)

This automatically defines the normal priority as midrange between the highest and lowest possible values.

Instead, I have decided to provide hardcoded values for the sake of clarity.

How to Use Defined Priority Levels

Now that we’ve established our priority levels, let’s see how to apply them when creating tasks.

Key point: Always use the defined macros (e.g., configPRIORITY_NORMAL) when setting task priorities. Avoid hardcoding values directly to improve code readability and maintainability. Calculations based on existing macros are also discouraged as they can lead to unexpected issues in the future.

Example: Creating a Task with Normal Priority

Here’s an example of creating a task with the configPRIORITY_NORMAL priority:

#include "FreeRTOS.h"
#include "task.h"


void myTask( void * pvParameters ) {
// Task code here
}

void createMyTask( void )
{
xTaskCreate( myTask, "MyTask",
configMINIMAL_STACK_SIZE,
NULL,
configPRIORITY_NORMAL,
NULL );
}

In this example:

  • myTask is the function that will be executed by the task.
  • configMINIMAL_STACK_SIZE is a FreeRTOS constant for the minimum stack size.
  • configPRIORITY_NORMAL is the macro we defined earlier.

 

By using configPRIORITY_NORMAL, we ensure that the task is created with the correct priority level with good readability.

Remember: Consistent use of priority macros enhances code clarity and simplifies future modifications. Avoid hardcoding values or using calculations based on existing macros.

Wrap-Up

By categorizing tasks into hard real-time, background, and normal application tasks, we’ve established a foundation for defining task priorities in FreeRTOS. This simple approach suggests using three distinct priority levels: high for real-time tasks, low for background tasks, and a middle ground for the majority of application logic.

This three-tier system offers a straightforward, efficient, and resource-friendly solution for many embedded systems. By leveraging the FreeRTOS scheduler, you can effectively manage task execution without the complexity of numerous priority levels.

While this approach is suitable for a wide range of applications, there may be scenarios where additional priority levels could be beneficial. In upcoming articles, we’ll explore these situations and discuss how to introduce extra levels carefully to avoid performance implications.

By adhering to these guidelines and consistently using defined priority macros, you’ll create well-structured, maintainable, and efficient FreeRTOS-based applications.