What happens if semaphore is given before it is taken?

Hi, what happens with binary and counting semaphores in the following scenario: 1) Task1 gives semaphore 2) Task 2 tries to take semaphore Task1 gave the semaphore before task2 tried to take it. Does task2 succceed in taking the semaphore or does task1 need to give it again? Thanks!

What happens if semaphore is given before it is taken?

There is a bit of a differnce on the type of semaphore, but for a binary semaphore, when Task1 gives the smeaphore it goes into the ready to be taken state (even if it is already there). With a counting semaphore, the ready count increases (unless it is at max). When Task2 takes the semaphore, it will be ready so Task2 will proceed. This is one of the big differences between using a semaphore and having task2 suspend itself and task1 resume it. That method does require that Task2 has done the suspend before Task1 does the Resume.

What happens if semaphore is given before it is taken?

Okay, thanks for the clarification. Is this written in some of the freertos docs as well? I did not find it explicitly stated anywhere that once a semaphore is given it can be taken EVEN if the taker was not trying to take it at the time of giving.

What happens if semaphore is given before it is taken?

This is a property of semaphores (and message queues) in every OS. At the moment a semaphore is given, there does not have to be a taker. The semaphore is patient and will keep its (given) state until some task will take it again. When two or more tasks try to take a binary semaphore, the task with the highest priority will get it.