xSemaphoreGive or xSemaphoreGiveFromISR in funciton called in interrupt handler

Hi,

I create and take a Semaphore in one task.


xSemaphore = xSemaphoreCreateBinary();
if( xSemaphore == NULL ){
	printf("pd_data_ready_sem create failed\r\n");
}
else	{
	printf("pd_data_ready_sem create success\r\n");
}

is_sampling = true;

// wait for give
xSemaphoreTake(xSemaphore, portMAX_DELAY);


and call xSemaphoreGive in a function which is called in interrupt handler.


if( xSemaphore != NULL )
{
	if( xSemaphoreGive( xSemaphore ) != pdTRUE )
	{
		printf("sem give failed\r\n");
	} else {
		printf("sem give success\r\n");
	}
} else {
	printf("sem is null\r\n");
}

but program stopped there and print nothing.

should I use xSemaphoreGiveFromISR instead ?

Yes. Don’t call printf from an isr either.

1 Like

Hi, Richard

thanks for your comment.
I think you mean the function called by isr is treated as isr.

yes, I have been told not using printf in isr, but what is the influence if it is used.
sometimes, program works well with printf called in isr.

Best
George

Also functions called by ‘primary’ ISR code are still part of the ISR and are executed in ISR context. Only FreeRTOS functions with the FromISR ending can be used in ISRs because ISRs are special.

There are 3 major reasons avoiding printf and similar functions in ISRs.

  1. They often require a lot of stack and usually the ISR stack isn’t that large
  2. Some printf implementations might allocate memory from heap (using malloc) which is usually not allowed/possible in ISRs (depends on the heap implementation, but usually it isn’t)
  3. printf and friends take a considerable amount of processing time and ISRs should as fast/short as possible. Also the low level output routine/driver called by printf might not be ISR safe.
1 Like

Just so it isn’t lost in the comments about printf, the fact that the function is called from an ISR, means it should call xSemaphoreGiveFromISR, not xSemaphoreGive, which also means it really should be passed a pointer to the ‘Was Woken’ flag, so the ISR knows it should generate a yield at its end.

Depending on the processor, you might be able to issue the Yield from ISR inside the function or that might not be allowed.