Real-time CPU
Linux real-time (RT) scheduling is critical for applications requiring deterministic latency, such as audio processing, robotics, or industrial control systems. This section covers RT kernel patches, scheduler configuration, and techniques to minimize latency for high-priority tasks.
Understanding Real-Time Scheduling Requirements¶
Real-time tasks must execute within strict deadlines, often requiring exclusive CPU access and predictable scheduling. Linux provides mechanisms to prioritize such tasks over non-RT workloads, but this requires specific kernel configurations and careful tuning.
Kernel Patches for Real-Time Support¶
Modern Linux kernels include PREEMPT_RT patches, which replace the standard kernel preemption model with a more aggressive, low-latency approach. Two variants exist:
- CONFIG_PREEMPT_RT: Lightweight patch for minimal latency improvements.
- CONFIG_PREEMPT_FULL: Full patch with deeper changes, suitable for strict real-time requirements.
Enabling these patches requires recompiling the kernel, as they are not part of standard distributions.
Example:
Real-Time Schedulers and Policies¶
Linux supports multiple scheduling policies for real-time tasks:
1. SCHED_FIFO (Fixed-Priority)¶
- Prioritizes tasks based on user-defined priorities (1–99).
- Tasks run until they block or yield the CPU.
- Use case: Critical tasks with strict deadlines.
2. SCHED_RR (Round-Robin)¶
- Similar to SCHED_FIFO but with time slices.
- Less common for hard real-time systems.
3. SCHED_DEADLINE¶
- Advanced scheduler for deadline-based tasks.
- Requires the
CONFIG_SCHED_DEADLINEkernel option. - Optimizes for both latency and throughput.
Example:
# Set a task's scheduling policy and priority
sudo chrt -t 99 -p 1234 <pid>
# Replace <pid> with the process ID
Latency Optimization Techniques¶
To minimize latency, adjust kernel parameters and system settings:
1. RT Period and Runtime¶
sched_rt_period_us: Defines the time window for RT tasks (e.g.,500000µs = 500 ms).sched_rt_runtime_us: Maximum CPU time allocated to RT tasks within the period.
Example:
# Set RT period and runtime (requires root)
echo 500000 > /proc/sys/kernel/sched_rt_period_us
echo 250000 > /proc/sys/kernel/sched_rt_runtime_us
2. CPU Affinity¶
Bind RT tasks to specific CPUs to reduce context switching.
Example:
3. Disable Non-Critical Services¶
Reduce background processes using:
Monitoring and Verification¶
Use tools to measure latency and validate configurations:
1. perf and latencytop¶
2. /proc Interface¶
Check RT parameters:
Key takeaways¶
- Real-time scheduling requires PREEMPT_RT kernel patches and careful configuration.
- Use SCHED_FIFO for hard deadlines and SCHED_DEADLINE for advanced workflows.
- Optimize latency by adjusting
sched_rt_period_us/sched_rt_runtime_usand binding tasks to CPUs. - Monitor with
perfandlatencytopto identify bottlenecks. - Prioritize critical tasks over non-RT workloads to ensure deterministic behavior.