Semaphore was taken although it was never given

sarahaka wrote on Sunday, February 24, 2019:

In my main function, I create a semaphore as so:

if (xSemaphoreISR == NULL){
		//log error
	printf("\t Failed to obtain semaphore for ISR... \n\r");

After I create the tasks, the tasks run. In one of the task I do the following:


    if( xSemaphoreTake( xSemaphoreISR, portMAX_DELAY ) == pdPASS ){
          printf("\n\r Safe Mode: Semaphore succesfully taken from ISR \n\r");

On the first run, surprisingly it does obtain the semaphore even though non of the other tasks gave it. How come?

richard_damon wrote on Sunday, February 24, 2019:

Binary Semaphores are created either full or empty depending on which function you use to create them. The vSemaphoreCreateBinary leaves the semaphore set on creation, so it is expected that the first take will work. This behavior works right if the semaphore is being used as a resource protection mechanism. If you use xSemaphore create binary, then the Semaphore is created empty, which is what you want for a syncronization semaphore like you are using.

The first usage may be better using a mutex to handle the priority inversion issue, the second can sometimes use the direct to task notification system if it will always be a particular task being notificed.