Embedded SystemUnit 711 min read

RTOS: Scheduling, Tasks, Synchronization & Resource Management

Unit 7 of Embedded System covers Real-Time Operating Systems (RTOS), including task scheduling (priority-based, round-robin), synchronization (mutexes, semaphores), inter-task communication (queues, mailboxes), and resource management in embedded systems. It explains how RTOS ensures deterministic behavior for time-cri

Key Concepts and How RTOS Works

1. What is an RTOS?

A Real-Time Operating System (RTOS) is an OS designed for deterministic execution of tasks within strict timing constraints. Unlike general-purpose OS (e.g., Windows, Linux), an RTOS guarantees:

  • Predictable response times (critical for embedded systems).
  • Low latency (minimized delay between task initiation and execution).
  • Efficient resource management (CPU, memory, I/O).

Why is it needed? Embedded systems (e.g., pacemakers, drone controllers, industrial robots) must respond to events within a guaranteed time frame. An RTOS ensures this by:

  • Using priority-based scheduling (higher-priority tasks run first).
  • Supporting preemptive multitasking (tasks can be interrupted if a higher-priority task arrives).
  • Providing synchronization mechanisms (to avoid race conditions).

2. Task Scheduling in RTOS

Scheduling determines which task runs when on the CPU. Common RTOS scheduling algorithms:

018.7537.556.2575Priority-Based75Round-Robin20Hybrid5
Approximate usage distribution of scheduling algorithms in embedded RTOS projects (based on industry surveys)

A. Priority-Based Scheduling

  • Tasks are assigned priority levels (e.g., 0 = lowest, 255 = highest).
  • The highest-priority ready task always runs.
  • If two tasks have the same priority, use round-robin (time-slicing).

Example: Automotive Airbag System

  • Task 1 (Priority 255): Crash detection (must run immediately).
  • Task 2 (Priority 100): Engine control (runs when no crash is detected).
  • Task 3 (Priority 10): Infotainment (lowest priority).
Highest Priority (255)Crash Detection(Preempts all)Medium Priority (100)Engine Control(Preempts low-priorityLow Priority (10)Infotainment (Runsonly when higher-prior
Priority-based scheduling in an automotive airbag system (higher numbers = higher priority)

B. Round-Robin Scheduling

  • Used for tasks of equal priority.
  • Each task gets a time slice (quantum) before switching.
  • Ensures fair CPU time distribution.

Example: Traffic Light Controller

  • Task 1: Red light (10s).
  • Task 2: Yellow light (2s).
  • Task 3: Green light (15s).
  • If all have the same priority, the RTOS switches between them in a loop.

3. Task States in RTOS

A task can be in one of five states:

State Description Transition Example
Ready Task is ready to run but waiting for CPU. Task completes I/O → moves to Ready.
Running Task is executing on the CPU. High-priority task arrives → preemption.
Blocked Task is waiting for an event (e.g., semaphore, I/O completion). Task requests a mutex → moves to Blocked.
Suspended Task is temporarily stopped (e.g., by a higher-level task). Debugger pauses task → Suspended.
Terminated Task has finished execution. Task calls exit() → Terminated.

4. Synchronization Mechanisms

To prevent race conditions (where two tasks access shared resources simultaneously), RTOS provides:

A. Mutexes (Mutual Exclusion)

  • Ensures only one task accesses a shared resource at a time.
  • Uses lock/unlock mechanism.
  • Problem: If a task forgets to unlock, it causes a deadlock.

Example: Bank ATM System

  • Shared Resource: Account balance database.
  • Task 1: Withdrawal (locks balance → updates → unlocks).
  • Task 2: Deposit (must wait if Task 1 is locking).
sequenceDiagram
    Task1->>Mutex: Lock()
    Task1->>Account: Read Balance
    Task1->>Account: Update Balance
    Task1->>Mutex: Unlock()
    Task2->>Mutex: Lock() (waits)
    Task2->>Account: Read Balance
    Task2->>Account: Update Balance
    Task2->>Mutex: Unlock()

B. Semaphores

  • Binary Semaphore (Mutex-like): 0 = locked, 1 = unlocked.
  • Counting Semaphore: Allows N tasks to access a resource (e.g., 3 printers → semaphore = 3).

Example: Printer Queue in an Office

  • Semaphore = 2 (only 2 printers available).
  • Task 1: Prints → semaphore decrements to 1.
  • Task 2: Prints → semaphore decrements to 0.
  • Task 3: Waits until a printer frees up.

C. Queues & Mailboxes

  • Queues: FIFO (First-In-First-Out) for inter-task communication.
  • Mailboxes: Stores single data items (e.g., sensor reading).

Example: Temperature Monitoring System

  • Sensor Task: Sends temperature data to a queue.
  • Display Task: Reads from the queue and updates the LCD.
flowchart TD
  A["Sensor Task"] -->|Sends (put)
  B["Queue/Mailbox: Temp Data"]
  B -->|Receives (get)
  C["Display Task"]
  D["LCD Update"]
  C -->|Updates
  D
Data flow in a temperature monitoring system using a queue

5. Interrupt Handling in RTOS

  • Hardware interrupts (e.g., button press, timer expiry) can preempt the running task.
  • RTOS disables interrupts during critical sections to avoid corruption.
  • Interrupt Service Routine (ISR) must be short (avoid complex operations).

Example: Emergency Stop Button in a Robot

  • ISR: Detects button press → sets a flag.
  • Main Task: Checks flag → stops robot motors.

6. Memory Management in RTOS

  • Static Allocation: Fixed memory for tasks (efficient but inflexible).
  • Dynamic Allocation: Uses heap memory (flexible but risky if misused).
  • Memory Protection: Prevents one task from corrupting another’s memory.

Example: Drone Flight Controller

  • Static Memory: Critical tasks (navigation, altitude control).
  • Dynamic Memory: Temporary data (sensor buffers).

In the Real World

  1. Pathao (Ride-Hailing App)

    • Uses an RTOS in its GPS tracking module to ensure real-time location updates for drivers and passengers.
    • Priority Scheduling: Emergency calls (high priority) preempt normal ride requests.
  2. Nepal Electricity Authority (NEA) Smart Grid

    • RTOS manages power distribution in real time.
    • Semaphores ensure only one control task adjusts voltage at a time.
  3. Medical Infusion Pumps (e.g., Baxter Healthcare)

    • Round-Robin Scheduling: Alternates between drug delivery and patient monitoring.
    • Mutexes: Prevent race conditions when updating drug dosage.
  4. Ncell’s 4G/5G Base Stations

    • RTOS handles real-time packet routing to minimize latency.
    • Queues: Manage data packets from multiple users without delay.

Worked Example: Traffic Light Controller with RTOS

Scenario: A traffic light system has:

  • Red Light (10s)
  • Yellow Light (2s)
  • Green Light (15s)
  • Emergency Vehicle Detection (High Priority)
Microcontroller (STM32)LED ArraysTimersHardware LayerTask 1: Pedestrian Button Handler (Priority 200)Task 2: Timer-Based Light Switching (Priority 150)Task 3: Emergency Override (Priority 255)RTOS LayerSemaphore for pedestrian crossingMutex for shared timer variablesSynchronizationTraffic Light Controller System
System architecture breakdown for the traffic light controller example

RTOS Implementation:

  1. Tasks:
    • TrafficControlTask (Priority 100)
    • EmergencyDetectionTask (Priority 255)
  2. Scheduling:
    • If an emergency vehicle is detected, EmergencyDetectionTask preempts TrafficControlTask.
  3. Synchronization:
    • Mutex protects the shared currentLightState variable.
// Pseudocode for Traffic Light RTOS Task
void TrafficControlTask(void *pvParameters) {
    while(1) {
        xSemaphoreTake(mutex, portMAX_DELAY); // Lock
        if (currentLightState == RED) {
            setGreenLight();
            vTaskDelay(15000 / portTICK_PERIOD_MS); // 15s delay
        } else if (currentLightState == GREEN) {
            setYellowLight();
            vTaskDelay(2000 / portTICK_PERIOD_MS); // 2s delay
        }
        xSemaphoreGive(mutex); // Unlock
    }
}

void EmergencyDetectionTask(void *pvParameters) {
    while(1) {
        if (emergencyVehicleDetected()) {
            xSemaphoreTake(mutex, portMAX_DELAY); // Lock
            setAllRedLights(); // Highest priority
            xSemaphoreGive(mutex); // Unlock
        }
        vTaskDelay(100 / portTICK_PERIOD_MS); // Check every 100ms
    }
}

Comparison: RTOS vs. General-Purpose OS (GPOs)

Feature RTOS General-Purpose OS (GPO)
Determinism Guaranteed response time. Best-effort timing.
Latency Microseconds to milliseconds. Milliseconds to seconds.
Scheduling Priority-based, preemptive. Time-sharing (round-robin).
Memory Usage Optimized for small footprint. Large memory overhead.
Use Case Industrial control, medical, automotive. Desktops, servers, smartphones.

Exam Tip

  1. Understand Priority Inversion:

    • A low-priority task holding a resource needed by a high-priority task can cause delays.
    • Solution: Use priority inheritance (temporarily boosts the low-priority task).
  2. Differentiate Between:

    • Mutex vs. Semaphore: Mutex = binary lock, Semaphore = counter.
    • Queue vs. Mailbox: Queue = FIFO buffer, Mailbox = single-item storage.
  3. Common Exam Questions:

    • Explain how an RTOS ensures deterministic behavior.
    • Draw a task state diagram and explain transitions.
    • Write a pseudocode example for a real-time system (e.g., pacemaker, drone).
  4. Key Formulas to Remember:

    • Task Response Time (WCRT): (Where = worst-case execution time, = period, = interference time.)
  5. Practical Scenario Questions:

    • "How would you implement a real-time system for an eSewa payment gateway to ensure transactions complete within 2 seconds?" Answer: Use priority scheduling for critical transactions, mutexes for database access, and semaphores for limiting concurrent connections.

Final Note: RTOS is the backbone of time-critical embedded systems. Mastering scheduling, synchronization, and task management will help you design systems for automotive, medical, industrial, and IoT applications. Always remember:

  • Higher priority ≠ always runs (must be ready).
  • Deadlocks happen if synchronization is misused.
  • Real-time ≠ fast (it’s about predictability).

Based on the PU BE Computer (PU) syllabus for Embedded System (ELX320), unit 7.

Discussion

Loading…