RTOS Concepts: Tasks, Exceptions, Semaphores, IPC

Classified in Electronics

Written on in English with a size of 13.89 KB

Task States: Suspended, Pended, Delayed

Suspended Task: A task is suspended when it is explicitly put into an inactive state by the operating system or another task. It does not participate in scheduling until it is resumed.

Pended Task: A task is pended when it is waiting for an event (e.g., a semaphore or message queue) to continue execution.

Delayed Task: A task is delayed when it is programmed to pause execution for a defined time (e.g., using a timer).

Exceptions and Their Classification

Exception: An event that disrupts the normal execution of a processor and forces it to execute special instructions.

Types of Exceptions

Synchronous Exceptions

Caused by internal processor events like division by zero or memory access errors.

Asynchronous Exceptions

Triggered by external events, such as a system reset or hardware failures.

Maskable Exceptions

Can be disabled or ignored by software.

Non-maskable Exceptions

Cannot be ignored and must be handled immediately.

Precise Exceptions

The processor knows exactly which instruction caused the exception.

Imprecise Exceptions

The exact instruction causing the exception is unclear.

Semaphore Types in RTOS

A semaphore is a kernel synchronization mechanism that controls access to shared resources among multiple tasks in an RTOS. It helps prevent race conditions and ensures mutual exclusion.

Binary Semaphore

A binary semaphore is the simplest form of semaphore. It can have only two states: 0 (unavailable) and 1 (available). It is commonly used for task synchronization.

Working of Binary Semaphore
  • When a task acquires the semaphore, its value changes from 1 to 0.
  • When the task releases the semaphore, its value changes back from 0 to 1.
  • If another task tries to acquire the semaphore while it is 0 (unavailable), it gets blocked until the semaphore is released.
Use Case

Used for signaling between tasks, such as when one task needs to wait for another task to complete.

Example: A printer device driver ensures that only one task can print at a time.

Counting Semaphore

A counting semaphore is used when multiple instances of a resource are available. It maintains a counter to track the number of available resources.

Working of Counting Semaphore
  • It starts with an initial count, representing the number of available resources.
  • Each time a task acquires the semaphore, the counter decreases.
  • Each time a task releases the semaphore, the counter increases.
  • If the counter reaches 0, tasks that request the semaphore are blocked until another task releases it.
Use Case

Useful for managing access to a limited pool of identical resources.

Example: A system with 5 database connections where multiple tasks can acquire and release them dynamically.


Mutex (Mutual Exclusion) Semaphore

A mutex is similar to a binary semaphore but with additional properties like ownership, priority inheritance, and recursive locking. It ensures that only one task at a time can access a resource.

Key Features of Mutex
  • Ownership: Only the task that acquires the mutex can release it.
  • Priority Inheritance: If a lower-priority task holds the mutex and a higher-priority task is waiting, the lower-priority task temporarily inherits the higher priority to prevent priority inversion.
  • Recursive Locking: A task can acquire the same mutex multiple times.
Use Case

Used for mutual exclusion when a shared resource needs exclusive access.

Example: Protecting a critical section where only one task can modify a shared variable.

RTOS Inter-Task Communication

Message Queues

A message queue is a kernel-managed buffer where tasks or interrupt service routines (ISRs) can send and receive messages asynchronously. It acts like a pipeline that temporarily holds messages from a sender until the receiver is ready to process them.

Characteristics of Message Queues
  • Supports multiple messages stored in FIFO (First-In-First-Out) order.
  • Allows communication between multiple sender and receiver tasks.
  • Decouples sender and receiver tasks (i.e., they do not need to execute at the same time).
  • Message size and queue length are configurable.

Message Queue Structure and Working

A message queue consists of the following components:

  • Queue Control Block (QCB): Stores metadata like queue ID, size, and pointers.
  • Queue Buffer: Stores the actual messages in a FIFO manner.
  • Task-Waiting List: Maintains tasks waiting for messages.
Message Queue Operation
  • Task A sends a message → The message is stored in the queue.
  • Task B receives the message → If no message is available, Task B waits.
  • Multiple tasks can send and receive messages, but the queue enforces an order.
Use Case Example

A temperature sensor task sends periodic readings to a data logger task using a message queue. The logger reads data when it is ready.


Pipes

A pipe is another inter-task communication mechanism that allows tasks to exchange data as a stream of bytes. Unlike message queues, pipes do not structure messages into discrete packets; they work as a continuous data stream.

Characteristics of Pipes
  • Data flows in a continuous byte stream.
  • Operates in FIFO order.
  • Supports unidirectional or bidirectional communication.
  • Tasks write to one end and read from the other.
Pipe Structure and Working

A pipe consists of:

  • Pipe Buffer: A memory region storing the stream of bytes.
  • Read and Write Descriptors: Allow tasks to access the pipe.
  • Task-Waiting List: Maintains tasks waiting to read or write.
Pipe Operation
  • Task A writes data to the pipe.
  • Task B reads data from the pipe when available.
  • If the pipe is full, the writing task waits.
  • If the pipe is empty, the reading task waits.
Use Case Example

A keyboard driver writes keystrokes to a pipe, while a text editor application reads the keystrokes and displays them on the screen.

Exceptions and Interrupts in Embedded Systems

In an embedded system, handling real-time events efficiently is critical. Exceptions and interrupts play a major role in ensuring timely responses to both expected and unexpected events. They improve reliability, responsiveness, and efficiency of the system.

What Are Exceptions and Interrupts?

Exception: A software-generated event caused by the processor when an instruction executes incorrectly or requires special handling.

Interrupt: A hardware-generated signal that tells the processor to pause its current execution and handle an external event immediately.

Role in Embedded System Design

Internal Error Handling & Special Conditions
Example: Division by Zero Exception
  • If a mathematical operation attempts to divide by zero, an exception handler prevents the system from crashing and provides a recovery mechanism.
  • This prevents unpredictable behavior and ensures system stability.
Example: Memory Access Error
  • If a task tries to access an invalid memory address, the system raises an exception.
  • The OS can then log the error, recover gracefully, or restart the faulty task.

Hardware Concurrency & Efficient Resource Management

Interrupts allow an embedded system to efficiently respond to multiple hardware events without constant polling.

Example: Sensor Data Acquisition
  • A drone's ultrasonic sensor detects obstacles. Instead of continuously checking the sensor (polling), the sensor triggers an interrupt when an obstacle is detected.
  • The CPU immediately processes the interrupt and instructs the drone to change direction.
Example: Real-Time Clock Interrupt
  • A real-time clock (RTC) generates periodic timer interrupts to schedule tasks accurately.
  • This is used in factory automation to trigger periodic measurements.

Service Requests & Device Communication
Example: Keyboard Input Handling
  • A user presses a key on an embedded device (e.g., ATM keypad). Instead of the CPU constantly checking for key presses, the keyboard generates an interrupt when a key is pressed.
  • The CPU pauses its current task, processes the key press, and resumes normal execution.
Example: Handling Network Packets
  • A router receives incoming data packets. Instead of constantly checking for new data, the network interface triggers an interrupt when a new packet arrives.
  • The CPU processes the data immediately, improving communication efficiency.

Interrupt Processing Steps

When an interrupt occurs, the processor follows these steps:

  • Save the current processor state (registers, program counter, etc.).
  • Load the interrupt handler function into the program counter.
  • Execute the handler function to process the event.
  • Restore the processor state and resume previous execution.

Interrupt Latency & Real-Time Performance

Interrupt latency is the delay between an interrupt request and the start of the interrupt handler execution.

In a real-time system, low latency is crucial to meet timing constraints.


Example: RTOS with Interrupt-Driven Scheduling

A real-time operating system (RTOS) relies on interrupts for scheduling high-priority tasks.

Example: In medical devices like a heart rate monitor, an interrupt ensures that critical heartbeat detection tasks execute on time.

Real-Time Systems and RTOS Characteristics

What is a Real-Time System?

A Real-Time System (RTS) is a computing system that must respond to inputs and complete tasks within a strict time constraint. The correctness of the system depends not only on logical correctness but also on the time at which the result is produced.

Key Characteristics of a Real-Time System
  • Deterministic: The system must respond within a predictable time.
  • Fast Response: Must process events quickly.
  • Reliability: Failure to meet deadlines can cause system failure.

Example: A self-driving car’s collision avoidance system must detect obstacles and respond in milliseconds. Delayed responses could cause accidents.


Characteristics of a Real-Time Operating System (RTOS)

Deterministic Behavior (Predictability)

An RTOS guarantees that critical tasks will execute within a fixed time limit (also known as a bounded response time).

Example: In an anti-lock braking system (ABS) in a car, braking commands must be executed within milliseconds.

The system must not delay execution due to lower-priority tasks.

Priority-Based Scheduling

RTOS uses priority-based scheduling to ensure that high-priority tasks execute first.

Example: In an aircraft flight control system, control tasks (e.g., altitude adjustment) must have higher priority than background tasks (e.g., data logging).

Minimal Interrupt Latency

Interrupt latency is the time between an interrupt request and the start of the interrupt handler.

RTOS optimizes context switching to minimize latency.

Example: In an industrial automation system, a conveyor belt must stop immediately if a fault is detected. Any delay can damage machinery or cause injuries.

Signals vs. Interrupts in RTOS

Both signals and interrupts are used to notify a task or a processor about an event that requires immediate attention. However, they differ in terms of their origin, behavior, and handling.

What is a Signal?

A signal is a software-generated event used for inter-process communication (IPC) or task synchronization. It is typically sent by one task (or process) to another to notify it of an event.

Key Features of Signals
  • Software-triggered: Sent by a task or the operating system.
  • Handled by the OS scheduler: The receiving task must check for and handle the signal.
  • Used for inter-task communication: Allows one task to notify another about an event.
Example of a Signal in RTOS

In a robotic control system, when the robot arm finishes a task, it sends a completion signal to the next task to begin.


What is an Interrupt?

An interrupt is a hardware-generated event that immediately stops the CPU’s current execution to handle an urgent task.

Key Features of Interrupts
  • Hardware-triggered: Occurs due to external events (e.g., sensor input, keypress).
  • Preempts running tasks: Interrupt service routines (ISRs) execute immediately.
  • Used for real-time event handling: Ensures immediate response to critical hardware events.
Example of an Interrupt in RTOS

In an automatic door system, a sensor detects motion and triggers an interrupt to open the door.

Related entries: