ENع
→FreeRTOS tasks
الدرس 38 · Bare metal versus an RTOS

FreeRTOS tasks and priorities

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

With FreeRTOS, each job in your firmware becomes a task: a C function with an endless loop, its own stack and a priority. On a single-core STM32F407VG, follow two tasks, sense (priority 2) and logger (priority 1), plus the idle task, millisecond by millisecond. You will see why the highest-priority Ready task always runs, how vTaskDelay frees the CPU, and how a waking task preempts a lower one. The OS course lessons on scheduling and real-time scheduling cover the general theory; here we use the FreeRTOS API.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 38 · تفاعلي
01 / 09

A task is an endless loop

A FreeRTOS task is a C function with an endless loop. This one, sense, reads a sensor, then waits. It must never return. The kernel, the core of the RTOS, lets several such tasks take turns on one CPU.

task      a C function that loops forever
          void sense(void *p) { for (;;) { ... } }
kernel    the core of the RTOS: it decides which task runs
rule      a task function must never return

// STM32F4DISCOVERY, FreeRTOS. FreeRTOSConfig.h: configTICK_RATE_HZ 1000 (1 tick = 1 ms)
#include "FreeRTOS.h"
#include "task.h"

void readSensor(void);   // about 0.5 ms of work (our example)
void writeLog(void);     // about 6 ms of work (our example)

void sense(void *p) {
  for (;;) {
    readSensor();
    vTaskDelay(5);
  }
}

void logger(void *p) {
  for (;;) {
    writeLog();
    vTaskDelay(20);
  }
}

int main(void) {
  // clock and pin setup omitted
  xTaskCreate(sense,  "sense",  256, NULL, 2, NULL);
  xTaskCreate(logger, "logger", 256, NULL, 1, NULL);
  vTaskStartScheduler();   // never returns while there is enough heap
  for (;;) {}
}
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A task is an endless loop

    A FreeRTOS task is a C function with an endless loop. This one, sense, reads a sensor, then waits. It must never return. The kernel, the core of the RTOS, lets several such tasks take turns on one CPU.

    task      a C function that loops forever
              void sense(void *p) { for (;;) { ... } }
    kernel    the core of the RTOS: it decides which task runs
    rule      a task function must never return
    
    // STM32F4DISCOVERY, FreeRTOS. FreeRTOSConfig.h: configTICK_RATE_HZ 1000 (1 tick = 1 ms)
    #include "FreeRTOS.h"
    #include "task.h"
    
    void readSensor(void);   // about 0.5 ms of work (our example)
    void writeLog(void);     // about 6 ms of work (our example)
    
    void sense(void *p) {
      for (;;) {
        readSensor();
        vTaskDelay(5);
      }
    }
    
    void logger(void *p) {
      for (;;) {
        writeLog();
        vTaskDelay(20);
      }
    }
    
    int main(void) {
      // clock and pin setup omitted
      xTaskCreate(sense,  "sense",  256, NULL, 2, NULL);
      xTaskCreate(logger, "logger", 256, NULL, 1, NULL);
      vTaskStartScheduler();   // never returns while there is enough heap
      for (;;) {}
    }
  2. A stack and a priority each

    xTaskCreate gives sense its own stack of 256 words (1,024 bytes on this 32-bit chip) and priority 2. A second task, logger, gets priority 1. A bigger number means more important. New tasks start Ready: able to run, waiting for the CPU.

    xTaskCreate(sense, "sense", 256, NULL, 2, NULL);
      function   sense
      name       "sense"     (for debugging)
      stack      256 words x 4 bytes = 1,024 bytes
      priority   2           (0 is the lowest)
    xTaskCreate(logger, "logger", 256, NULL, 1, NULL);
    both start in the Ready state
  3. The highest Ready task runs

    vTaskStartScheduler() hands the CPU to the kernel. It adds an idle task at priority 0, then runs the highest-priority Ready task: sense, priority 2. This chip has one core, so exactly one task is Running at a time.

    vTaskStartScheduler();
      creates   idle task, priority 0
      Ready     sense (2), logger (1), idle (0)
      picks     the highest: sense (2)  ->  Running
    one core (Cortex-M4)  ->  one Running task
    t = 0 ms
  4. vTaskDelay: wait without the CPU

    sense reads its sensor in 0.5 ms, then calls vTaskDelay(5). It moves to Blocked until 5 ticks pass; our tick is 1 ms. A Blocked task uses no CPU time and cannot be picked to run.

    t = 0 .. 0.5 ms   sense runs readSensor()
    vTaskDelay(5)   ->  Blocked until tick 5
    tick       1000 Hz  ->  1 ms each (configTICK_RATE_HZ)
    Blocked    uses no CPU time
  5. Now the lower task runs

    With sense blocked, the highest-priority Ready task is logger, priority 1, so it runs. It needs 6 ms of CPU to format and write a log line. logger never mentions sense: the kernel alone decides who runs.

    Ready      logger (1), idle (0)
    picks      logger  ->  Running from 0.5 ms
    needs      6 ms of CPU for one pass
    by 5 ms   4.5 ms done, 1.5 ms left
  6. Preemption at the 5 ms tick

    At tick 5 sense's delay ends and it becomes Ready. 2 beats 1, so the kernel stops logger at once, mid-line, saves its registers on logger's own stack and runs sense. That is preemption.

    tick 5     sense: Blocked -> Ready
    compare    sense 2 > logger 1
    switch     logger -> Ready, registers saved on its stack
               sense  -> Running
    preemption: a higher-priority task takes the CPU at once
  7. Back where it stopped

    sense blocks again after 0.5 ms, until tick 10. logger resumes exactly where it stopped, from its saved registers. It finishes at 7 ms and calls vTaskDelay(20), so it is Blocked until tick 27.

    t = 5 .. 5.5   sense runs, then Blocked until tick 10
    t = 5.5 .. 7   logger resumes from its stack, finishes
    vTaskDelay(20)  ->  logger Blocked until tick 27
  8. Nothing Ready: the idle task

    From 7 ms none of our tasks is Ready, so the idle task runs. It can put the CPU into a low-power mode. At tick 10 sense wakes and preempts idle, exactly as it preempted logger.

    t = 7 .. 10    idle runs (priority 0)
    tick 10     sense wakes, preempts idle
    t = 10 .. 10.5  sense, then idle again
    idle hook  a common place to enter a low-power mode
  9. A task that never blocks

    Delete vTaskDelay(5) and sense is always Ready. Priority 2 always wins, so logger and idle never run again: they starve. With priorities, high-priority tasks must block to wait for time or an event.

    what if line 4 is deleted?
      sense    always Ready  ->  always Running
      logger   never runs (starved)
      idle     never runs (starved)
    rule: high-priority tasks must block

اختبار يتاح بعد الخطوة الأخيرة.