Module 8 · 12 marks · Design, criticality & testing
Real-time software design
Real-time software must produce correct results within strict time limits. Its design starts from stimuli and timing constraints, structures the system as concurrent processes run by a real-time executive, and uses patterns, state machines, scheduling and timing analysis to meet every deadline.
Medium 45 minSyllabus: “Real-time software design”
Mark as
The idea in one minute
A fire station on alert is a real-time system. Some events are regular — the duty officer checks the equipment every hour (periodic stimuli); others arrive at any moment — an emergency call (aperiodic). The response must be right and on time: a perfect rescue that arrives an hour late is a failure. The station has a strict priority order — emergencies first, paperwork last — and a dispatcher who assigns crews, exactly like a real-time executive scheduling processes.
Key points — the night-before list
Real-time system: correctness depends on the results AND the time they are produced. Hard real-time — a missed deadline is a failure; soft — late results only degrade service.
Embedded systems are software inside hardware devices; most are real-time. Model them as stimulus → response, with sensors and actuators.
Periodic stimuli occur at predictable intervals (polled sensors); aperiodic stimuli occur irregularly and are usually signalled by interrupts.
Architecture: sensor-control processes → data processor → actuator-control processes, running concurrently under a real-time executive.
Patterns (Sommerville): Observe and React (alarms), Environmental Control (sensors + actuators, e.g. pump or ABS), Process Pipeline (data acquisition, signal processing).
Data acquisition: producer → circular buffer → consumer with mutual exclusion. Rate-monotonic test: U = Σ Cᵢ/Tᵢ ≤ n(2^(1/n) − 1) (→ 0.69 for large n).
01Real-time and embedded systems
A real-time system is one whose correctness depends not only on the results it produces but also on when it produces them. An answer that is right but late is wrong. Real-time does not mean 'fast' — it means predictable: the system must be shown to meet its timing requirements under all specified conditions.
Hard real-time
The system is incorrect if a result is not produced by its deadline
A missed deadline may be catastrophic
Timing must be guaranteed and proven (worst case, not average)
e.g. car anti-lock brakes, cardiac pacemaker, flight control, lift-door safety interlock
Soft real-time
Operation is degraded, not wrong, if timing requirements are occasionally missed
Late results lose value gradually
Average performance and percentiles matter
e.g. online banking, railway reservation, video streaming, HLAMS status queries
Some books add firm real-time: a late result is useless (discarded) but an occasional miss is tolerable — a sensor sample that arrives after the next sample, for instance. An embedded system is a computer system built into a larger device — a washing machine, a lift controller, a fire-alarm panel. Most embedded systems are real-time, and many real-time systems are embedded, but the terms are not identical: a stock-exchange trading system is real-time without being embedded.
PSC favourite
PSC 2018: applications like banking and reservation need a soft real-time system. PSC 2025: a hard real-time control system must ensure that every deadline is met; a miss is catastrophic — not 'average response time below a threshold'.
02The stimulus/response model, sensors and actuators
Real-time systems are naturally described as stimulus/response systems: each stimulus must be answered by its response within a stated time limit. The behaviour is therefore defined by listing the stimuli the system receives, the responses it must produce and the time allowed for each.
Periodic stimuli
Occur at predictable time intervals
Usually generated by the system itself polling sensors
e.g. read every smoke detector twice a second; sample the tank level every 500 ms
Aperiodic stimuli
Occur irregularly and unpredictably
Usually signalled through the computer's interrupt mechanism
e.g. a manual fire call-point pressed; mains power failure; an I/O transfer completing
Stimuli come from sensors, which collect information from the system's environment (smoke, temperature, water level, door position), and responses go to actuators, which change that environment (sirens, pump motors, door releases, valves). Because different stimuli have different timing demands, a simple sequential loop that checks everything in turn is usually inadequate. Real-time systems are instead built as cooperating concurrent processes, controlled by a real-time executive:
TextGeneric real-time system architecture
Sensor --> [ Sensor control ] --stimulus--+
Sensor --> [ Sensor control ] --stimulus--+--> [ Data processor ]
Sensor --> [ Sensor control ] --stimulus--+ |
| response
+-------------------------+
| | |
v v v
[ Actuator control ] [ Actuator control ] [ Actuator control ]
| | |
Actuator Actuator Actuator
One process per class of sensor and actuator, all running concurrently
under the real-time executive, which schedules them to meet deadlines.
Tip
Running example: a KSHB apartment complex has a fire and intrusion alarm, an overhead-tank pump controller and smart water meters. Each illustrates one of the three architectural patterns in the next section.
03Architectural patterns for real-time systems
Sommerville describes three architectural patterns that recur in embedded and real-time systems. They describe the overall organisation of processes; a real system may combine them.
Pattern
Description
Stimuli
Responses
KSHB example
Observe and React
Input values of a set of sensors of the same type are collected and analysed; when an event is detected, the system reacts by initiating a process to handle it
Values from sensors indicating that some event has occurred
Outputs to displays, alarm triggers, signals to reacting systems
Fire and intrusion alarm: detectors are monitored; a confirmed fire triggers sirens, door release and a call to the fire station
Environmental Control
The system includes sensors giving information about the environment and actuators that can change it; it adjusts actuator settings in response to changes detected by sensors
Values from sensors; status of actuators
Control signals to actuators; display information
Overhead-tank pump controller: level and sump sensors drive the pump motor
Process Pipeline
Data is transformed from one representation to another before processing; transformations run as a sequence of concurrent processes linked by buffers
Input values from sensors or another system
Display data, control signals, processed data
Water-meter data acquisition: collect → filter → compute consumption → store and bill
Each pattern implies a process structure. Observe and React has a monitoring process per sensor type plus processes for each reaction (sounder, lights, communication). Environmental Control has sensor monitors, a controller, actuator drivers and often feedback monitoring of the actuators themselves (is the pump actually running?). Process Pipeline is a producer–consumer chain in which each stage runs at its own rate, decoupled by buffers.
PSC favourite
Match the pattern: alarms and monitoring → Observe and React; thermostats, ABS brakes, pump or valve control → Environmental Control; data acquisition, digital signal processing, video processing → Process Pipeline.
04The real-time design process and state-machine modelling
Designing a real-time system
Identify the stimuli and the required responses
List every stimulus the system must process and the response each needs — e.g. smoke detected → sound alarm, release doors, call fire station.
Identify the timing constraints
For each stimulus and response, record the deadline (and, for periodic stimuli, the frequency) — e.g. sirens within 1 s of confirmation.
Aggregate into concurrent processes
Group stimulus and response processing into concurrent processes — often one process per class of stimulus and response.
Design the algorithms
Design an algorithm for each stimulus/response class that can meet its timing requirement; this may rule out heavyweight techniques with unpredictable overheads.
Design the scheduling system
Choose priorities and a scheduling scheme that start processes in time to meet their deadlines.
Data and timing analysis
Design the data shared between processes (buffers, mutual exclusion) and check the worst-case timing of the whole set; integrate under a real-time executive or RTOS.
Timing constraints may require extensive simulation and experiment, and the order of steps is not rigid — the platform (hardware and RTOS) may have to be chosen early because it affects every timing figure. Sommerville warns that, for hard real-time systems, design techniques with significant run-time overheads (including some object-oriented features) may need to be avoided or used with care.
State machines are the natural model: each stimulus can cause a transition from one state to another, and the actions on the transition are the responses. Sommerville's examples include a microwave oven and a petrol-pump controller. The KSHB pump controller below follows the Environmental Control pattern:
State
Stimulus [guard]
Next state
Response (action)
Idle
Tank level low [sump not empty]
Pumping
Start pump motor; log start time
Pumping
Tank level high
Idle
Stop pump motor
Pumping
Sump empty (dry run)
DryRunTrip
Stop pump; sound buzzer; send SMS to caretaker
DryRunTrip
Sump refilled [10 minutes elapsed]
Idle
Clear buzzer
Pumping
Motor over-current
Fault
Stop pump; raise alarm
Pumping
Run time > 45 minutes
Fault
Stop pump (level sensor suspected); raise alarm
Fault
Manual reset by caretaker
Idle
Clear alarm; resume automatic control
Pump-controller state machine. The run-time limit is a timing constraint that protects against a failed high-level sensor.
05Real-time executives (RTOS)
A real-time executive (or real-time operating system, RTOS) is a compact, specialised OS whose job is to run a real-time system's processes: it starts and switches them and hands out processor time and memory. It is usually much smaller than a general-purpose OS and may omit facilities such as a file system. Commercial and open examples include VxWorks, QNX and FreeRTOS.
Component
Responsibility
Real-time clock
Provides information for process scheduling by generating periodic interrupts (clock ticks)
Interrupt handler
Manages aperiodic requests for service
Scheduler
Examines the processes that can be executed and chooses one of them to run
Resource manager
Allocates appropriate memory and processor resources to the process chosen for execution
Dispatcher
Starts the execution of the chosen process
Configuration manager (larger systems)
Dynamically reconfigures the system's hardware and software — modules can be replaced or upgraded without stopping the system
Fault manager (larger systems)
Detects hardware and software faults and takes action (e.g. switching to backup disks) so the system continues to operate
Interrupt level — the highest priority, for processes that need a very fast response; the real-time clock process is one of them.
Clock level — allocated to periodic processes.
Background — processes with no real-time deadline (e.g. self-checking), run when processor capacity is free.
When an interrupt occurs, control transfers automatically to a predetermined memory location holding a jump to the interrupt service routine (ISR); further interrupts are disabled while it runs, so ISRs must be short, simple and fast — typically they record the event and signal a process. For periodic processes, each clock tick causes an interrupt that schedules the process manager, which picks the periodic processes that are due. The executive then performs the switch: scheduler chooses the process → resource manager allocates memory and a processor → dispatcher starts it.
Non-pre-emptive scheduling
A scheduled process runs until it completes or blocks (e.g. waiting for I/O)
Simple and predictable for short tasks
A long task can make an urgent one miss its deadline
Pre-emptive scheduling
A running process can be stopped when a higher-priority process needs service
Standard in real-time executives
Algorithms: round robin, rate-monotonic (fixed priority: shorter period → higher priority), earliest deadline first
Priority inversion
A low-priority process holding a shared resource can block a high-priority one while medium-priority processes keep running. This famously reset NASA's Mars Pathfinder lander in 1997; the fix is priority inheritance — the resource holder temporarily inherits the blocked process's priority.
06Monitoring and control systems; data acquisition
Monitoring and control systems form a large family of real-time systems that watch their sensors all the time and respond to what they see. A monitoring system reports what the sensors show; a control system also uses the readings to drive actuators. Sommerville's burglar-alarm example monitors door, window and movement sensors and, on detecting an intruder, switches on lights, sounds an alarm and calls the police with a synthesised voice message. The KSHB fire-alarm panel works the same way:
Stimulus / response
Type
Timing requirement
Smoke and heat detectors
Periodic
Each detector polled twice per second
Manual call point pressed
Aperiodic (interrupt)
Handled within 100 ms
Mains power failure
Aperiodic (interrupt)
Switch to battery within 50 ms
Sirens and strobe lights
Response
On within 1 s of a confirmed alarm
Fire-exit door release
Response
Doors unlocked within 2 s
Call to fire station (101)
Response
Call started within 10 s, giving building and zone
Stimuli and timing requirements (illustrative figures for the KSHB complex)
The process architecture follows directly: a detector-polling process (periodic), call-point and power-management processes (interrupt-driven), an alarm-controller process that co-ordinates, sounder, door-release and external-alert processes that drive actuators, a panel-display process, and a self-test background process. The step-through at the end of this page follows one alarm from interrupt to fire-station call.
Data acquisition systems gather readings from sensors so that they can be processed and analysed afterwards — Sommerville's example is neutron-flux monitoring in a nuclear reactor. Readings can arrive faster than they can be processed, so the design must guarantee that each value is captured before the sensor moves on to the next one. The standard solution is a producer–consumer structure with a circular (ring) buffer: the sensor (producer) process adds readings, the processing (consumer) process removes them, and each runs at its own rate. The two must be mutually excluded from the same buffer slot, the producer must not add to a full buffer and the consumer must not take from an empty one.
CA thread-safe ring buffer in C (POSIX threads): the mutex gives mutual exclusion, the condition variables block on full and empty
#include <pthread.h>#define SIZE 8 /* ring-buffer capacity */
typedef struct { int sensorId; int value; } Reading;
static Reading buf[SIZE];
static int head = 0, tail = 0, count = 0; /* head: next write, tail: next read */
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t notFull = PTHREAD_COND_INITIALIZER;
static pthread_cond_t notEmpty = PTHREAD_COND_INITIALIZER;
/* called by the sensor (producer) process */
void put(Reading r) {
pthread_mutex_lock(&lock);
while (count == SIZE) /* full: producer waits */
pthread_cond_wait(¬Full, &lock);
buf[head] = r;
head = (head + 1) % SIZE; /* wrap around: circular */
count++;
pthread_cond_signal(¬Empty);
pthread_mutex_unlock(&lock);
}
/* called by the processing (consumer) process */
Reading get(void) {
pthread_mutex_lock(&lock);
while (count == 0) /* empty: consumer waits */
pthread_cond_wait(¬Empty, &lock);
Reading r = buf[tail];
tail = (tail + 1) % SIZE;
count--;
pthread_cond_signal(¬Full);
pthread_mutex_unlock(&lock);
return r;
}
07Timing analysis and real-time programming
Timing analysis works out how often each process has to run, and how long it may take, so that no input is missed and every response is on time. Three figures are needed for every process: its deadline (the time by which a stimulus must be processed and a response produced), its frequency (how many times per second it must run, i.e. its period) and its execution time — the worst-case execution time (WCET), not the average.
Polling a sensor with period T: worst-case detection delay = T
To meet deadline D with handling time C: T + C ≤ D ⇒ T ≤ D − C
CPU utilisation of n periodic tasks: U = Σ Cᵢ / Tᵢ (must be ≤ 1)
Rate-monotonic (fixed priority) guarantee: U ≤ n(2^(1/n) − 1)
n = 1: 1.000 n = 2: 0.828 n = 3: 0.780 n → ∞: ln 2 ≈ 0.693
Earliest deadline first (pre-emptive): schedulable if U ≤ 1
The rate-monotonic bound (Liu and Layland, 1973) is sufficient, not necessary: a set above it may still be schedulable, but needs exact analysis.
Programming languages. Hard real-time systems may still be written partly in assembly language to meet tight deadlines. C is the most widely used language, with an RTOS API and safety subsets such as MISRA C. Ada (designed for the US Department of Defense, standardised in 1983) was built for embedded and real-time work: it has tasks, protected objects, rendezvous and, in its Ravenscar profile, a deterministic tasking subset for safety-critical code.
Standard Java is not suited to hard real-time: the time at which threads run cannot be specified, garbage collection can pause the program unpredictably, the sizes of queues for shared resources cannot be discovered, JVM implementations vary, and there is no way to analyse a thread's space or CPU needs. The Real-Time Specification for Java (RTSJ) addresses this with real-time threads that are not interrupted by the garbage collector, scoped and immortal memory, asynchronous event handling, high-resolution timers and direct access to physical memory.
PSC favourite
For an exam numerical: compute U = Σ C/T first. If U > 1 the set is definitely unschedulable; if U ≤ n(2^(1/n) − 1) it is schedulable by rate-monotonic priorities; in between, the bound is inconclusive.
Step through · Fire alarm: from interrupt to fire-station call
step 1 / 9
Step 1: Interrupt: zone 3 smoke detected
A detector in zone 3 raises an interrupt — an aperiodic stimulus. Control jumps to the interrupt service routine at the highest (interrupt) priority level.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1How often must the power monitor run?
The fire-alarm panel must switch to battery within D = 50 ms of a mains failure. The power-monitor process polls the supply voltage; detecting the failure and switching over takes C = 10 ms in the worst case. Find the longest acceptable polling period and the minimum polling frequency. Would an interrupt be better?
EX 2Rate-monotonic schedulability of the panel's periodic processes
The panel's periodic processes are: power check (C = 10 ms, T = 40 ms), panel refresh (C = 30 ms, T = 200 ms) and detector polling (C = 20 ms, T = 500 ms). Assign rate-monotonic priorities and test schedulability.
EX 3Designing the pump controller (Environmental Control)
Apply the real-time design process to the overhead-tank pump controller of a KSHB block.
EX 4Tracing a ring buffer
A ring buffer has 4 slots (indices 0–3); head = tail = count = 0. Trace: put A, put B, get, put C, put D, put E, get, get. What happens if a sixth put follows without a get?
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Classify each as hard or soft real-time: (a) car anti-lock braking; (b) online railway reservation; (c) cardiac pacemaker; (d) video streaming; (e) HLAMS EMI status queries; (f) lift-door safety interlock.
Q2
Three periodic tasks have (execution time, period) = (1, 4), (2, 6) and (1, 10) ms. Are they schedulable by rate-monotonic scheduling? By earliest deadline first?
Q3
The high-level float switch of a water tank must stop the pump within 2 s of the water reaching the top. Stopping the pump takes 200 ms. What is the maximum polling period for the switch? If the switch reading is debounced over two consecutive polls, what is it then?
Q4
Match each real-time executive component to its job: real-time clock, interrupt handler, scheduler, resource manager, dispatcher, fault manager. Jobs: (i) starts the chosen process; (ii) handles aperiodic service requests; (iii) allocates memory and a processor; (iv) produces periodic ticks for scheduling; (v) detects faults and switches to backups; (vi) chooses the next process to run.
Q5
Name the Sommerville architectural pattern for: (a) a building-management system that turns air-conditioning up or down from temperature readings; (b) a system that records vibration from bridge sensors, filters noise, computes spectra and stores results; (c) a gas-leak monitor that raises an alarm and shuts a valve when a sensor reading exceeds a threshold.
Exam traps
Real-time does not mean fast — it means guaranteed, predictable timing. A slow system that always meets its deadlines is real-time; a fast one that occasionally misses a hard deadline is not.
Banking and reservation systems are soft real-time (PSC 2018 key); ABS brakes and pacemakers are hard real-time.
Periodic stimuli are usually handled by polling at clock level; aperiodic stimuli by interrupts at interrupt level. Don't swap them.
Priority order in Sommerville's executive: interrupt level (highest, includes the real-time clock process) > clock level (periodic processes) > background (no deadlines).
The rate-monotonic bound n(2^(1/n) − 1) is sufficient but not necessary; EDF can schedule any independent pre-emptible task set with U ≤ 1.
Standard Java is unsuitable for hard real-time because of uncontrolled garbage collection and thread scheduling; the RTSJ adds real-time threads and memory areas.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.