What is a Semaphore ?

In programming, a semaphore is a variable that is shared between threads to achieve synchronization and to avoid shared resource problem in multiprocessing environment.

Use of Semaphore:

A semaphore is a signaling mechanism in which task that is waiting on a semaphore can be signaled by another task. In other words, when a TaskA completed its work, then it will increment a flag by 1 (also called Give mechanism) and then this flag is received by another task let’s say TaskB, means that it can perform its work now. When TaskB finished its work then the flag will be decreased by 1 (also called Take mechanism).

So, basically, it is a “Give” and “Take” mechanism and semaphore is an integer variable that is used to synchronize threads or task

Need of Semaphore:

let’s say there is Low Priority Task is running and getting some sensors data, A High Priority Task can pre-empts the Low Priority Task at any point. But if the Low Priority Task have the semaphore, and it doesn’t release it until it comes out of the critical section(to avoid data loss and malfunctioning of the whole application), then High Priority Task have no other option but to wait for the semaphore, and it can’t pre-empts the Low Priority Task.

So, wherever we need to protect data loss, Semaphore plays an important role.

it prevent other threads or tasks from accessing a shared resource or critical section.

Types of Semaphore in FreeRTOS:

Semaphore are of two types.

1. Binary Semaphore

2. Counting Semaphore

1. Binary Semaphore: A Binary Semaphore is called Binary because either it is there 1 or it is not 0. So, a Task either have the semaphore or it simply doesn’t have. Lets say, we have two tasks, TaskA and TaskB. TaskA sends data to TaskB when it is completed, so TaskB continuously checks the value of flag if there is 1, if it is 1, then it can read the data else it has to wait until it becomes 1. After taking the data, TaskB decrement the value and make it 0 again so that TaskA can again send the data to TaskB.

we can use this concept between tasks or between tasks and interrupt.

2. Counting Semaphore: counting semaphore is similar to binary semaphore except It has values greater than 0. This semaphore is used for counting events. In this usage scenario, an event handler will ‘give’ a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will ‘take’ a semaphore each time it processes an event (decrementing the semaphore count value).

    Leave a Reply

    Your email address will not be published.

    Need Help?