Semaphore in Embedded C: What It Is and How It Works
Embedded C, a semaphore is a synchronization tool used to control access to shared resources by multiple tasks or processes. It helps prevent conflicts by signaling when a resource is free or busy, ensuring safe and orderly use.How It Works
Think of a semaphore like a traffic light for tasks in an embedded system. When a task wants to use a shared resource, it checks the semaphore. If the semaphore shows green (available), the task proceeds and changes the semaphore to red (busy). If the semaphore is red, the task waits until it turns green again.
This mechanism prevents two tasks from using the same resource at the same time, which could cause errors or unpredictable behavior. Semaphores usually hold a count that represents how many units of the resource are free, allowing multiple accesses if the count is more than one.
Example
This example shows a simple binary semaphore in Embedded C controlling access to a shared variable between two tasks.
#include <stdio.h> #include <stdbool.h> volatile int shared_data = 0; volatile bool semaphore = true; // true means resource is free void task1() { if (semaphore) { semaphore = false; // take the resource shared_data += 1; // use the resource printf("Task 1 updated shared_data to %d\n", shared_data); semaphore = true; // release the resource } else { printf("Task 1 waiting for resource\n"); } } void task2() { if (semaphore) { semaphore = false; shared_data += 10; printf("Task 2 updated shared_data to %d\n", shared_data); semaphore = true; } else { printf("Task 2 waiting for resource\n"); } } int main() { task1(); task2(); return 0; }
When to Use
Use semaphores in embedded systems when multiple tasks or interrupts need to share limited resources like memory, sensors, or communication buses. They help avoid conflicts and data corruption by ensuring only one task accesses the resource at a time.
For example, if two tasks try to write to the same display or sensor, a semaphore can make one wait until the other finishes. This is common in real-time operating systems (RTOS) where tasks run concurrently.
Key Points
- A semaphore controls access to shared resources in embedded systems.
- It acts like a signal or flag to indicate if a resource is free or busy.
- Binary semaphores have two states: free (1) or busy (0).
- Counting semaphores allow multiple simultaneous accesses up to a limit.
- Semaphores prevent race conditions and data corruption.