Glossary · Automation software engineering and architecture
Critical section
German: Kritischer Abschnitt
In concurrent programming, a critical section is a part of a program that accesses a shared resource, such as a variable, data structure or device, and must not be executed by more than one task or thread at the same time. Mutual exclusion mechanisms, such as mutexes, semaphores or disabling interrupts, protect it.
- Software engineering
In one sentence
A critical section is code accessing a shared resource that must not run in more than one task at a time, protected by mutual exclusion.
Example
Updating the recipe structure shared by the HMI task and the sequence task is placed in a critical section, so the sequence never reads a half-updated recipe.
How it applies
- Engineering: Keep critical sections short. Long critical sections block other tasks, increase response times and contribute to jitter; in real-time systems, they can lead to priority inversion, where a high-priority task waits for a low-priority one.
- Design: Acquire locks in a consistent order to avoid Deadlock. Where possible, replace locking with Atomic operation access, message queues or double buffering.
- Documentation: Developer documentation should list shared resources, which mechanism protects each of them and any locking order rules. Controller-specific mechanisms differ between platforms, so document the ones used in the project.
Critical section vs. atomic operation
An Atomic operation is indivisible by itself and needs no lock. A critical section makes a longer sequence behave as indivisible by preventing concurrent access. Critical sections cover more cases but have a higher cost in blocking and complexity.