0
0
Power-electronicsConceptBeginner · 3 min read

Critical Section in Embedded C: Definition and Usage

A critical section in Embedded C is a part of the code where shared resources are accessed and must not be interrupted to avoid data corruption. It ensures that only one task or interrupt can execute that code at a time by temporarily disabling interrupts or using locks.
⚙️

How It Works

Imagine you and a friend are sharing a notebook to write notes. If both write at the same time, the notes get mixed up and confusing. To avoid this, you take turns writing, making sure only one person writes at a time. This is similar to a critical section in embedded programming.

In Embedded C, a critical section is a small part of the program where shared data or hardware is accessed. To keep this access safe, the program temporarily stops other tasks or interrupts from running. This way, the code inside the critical section runs without interruption, preventing errors like corrupted data or unexpected behavior.

💻

Example

This example shows how to protect a shared variable by disabling interrupts before changing it and enabling them after. This prevents other code from interrupting and changing the variable at the same time.

c
#include <stdint.h>
#include <stdbool.h>

volatile uint8_t shared_counter = 0;

void enter_critical_section(void) {
    __disable_irq();  // Disable interrupts
}

void exit_critical_section(void) {
    __enable_irq();   // Enable interrupts
}

void increment_counter(void) {
    enter_critical_section();
    shared_counter++;  // Safe update
    exit_critical_section();
}

int main(void) {
    increment_counter();
    increment_counter();
    return 0;
}
🎯

When to Use

Use critical sections when multiple parts of your embedded program share data or hardware resources that can be changed unexpectedly, such as counters, flags, or communication buffers. For example, if an interrupt and the main program both update the same variable, a critical section prevents them from interfering with each other.

This is important in real-time systems where timing and data integrity matter, like controlling motors, reading sensors, or communicating over networks.

Key Points

  • A critical section protects shared resources from simultaneous access.
  • It usually works by disabling interrupts or using locks.
  • Keep critical sections short to avoid delaying other important tasks.
  • Used in embedded systems to maintain data integrity and predictable behavior.

Key Takeaways

A critical section prevents data corruption by allowing only one access at a time.
Disabling interrupts is a common way to protect critical sections in Embedded C.
Use critical sections when shared resources can be accessed by interrupts or multiple tasks.
Keep critical sections as short as possible to maintain system responsiveness.