Using taskENTERCritical() and taskEXITCritical() within function, called in a Task

Hi everyone,

Firstly, I created a Task with a vTaskDelay of 1 second, which has a function call. Two questions.

  1. Does using taskENTERCritical() and taskEXITCritical() in the function, called in the task work?
  2. Is it right to do that?

I have print messages in the function call among tasks which I am treating as shared resource and using taskENTER and taskEXIT.

Thanks in advance,

-ZoroIchimonji

Hi @ZoroIchimonji

Entering and exiting the critical section using taskENTER_CRITICAL() and taskEXIT_CRITICAL() should work inside the task function. Make sure to NOT call any FreeRTOS API while inside the critical section.

It seems that you are using printf inside the critical section. While it will work, it is not recommended as printf may take longer to execute. taskENTER_CRITICAL() and taskEXIT_CRITICAL() implement critical section by disabling interrupts and therefore, are recommended for very short and deterministic critical sections. Consider using mutex to serialize printf calls.

1 Like

Hi @karahulx

Thanks for the response! There is one more thing.

While it seems what you suggested was for when the printf messages are withing the task but enveloped between task*Critical(), what about the following scenario?

void CalledFunction()
{
  taskENTERCritical();
  printf("In Called Function\r\n");
  taskEXITCritical();
  
  //Something else

return;
}

static void Task1(void * pvParameters){
{

  for(;;){
  //Something here
  CalledFunction();
  //Something there
  vTaskDelay(1000/portTICK_PERIOD_MS);
}

}

Can you also comment on this scenario?

Thanks in advance,

-ZoroIchimonji

It is still the same thing. What you are doing is calling printf in a critical section implemented using taskENTER_CRITICAL / taskEXIT_CRITICAL which is not a good idea as @karahulx already explained. Why do you want to use critical section - probably to ensure that the output from multiple tasks is not mangled, right? You should use mutex in this case -

SemaphoreHandle_t mutex;

void CalledFunction()
{
  if( xSemaphoreTake( mutex, pdMS_TO_TICKS( 1000 ) ) == pdPASS )
  {
    printf("In Called Function\r\n");
    xSemaphoreGive( mutex );
  }
  else
  {
    /* Failed to acquire mutex. Perform error handling. */
  }
  //Something else
}

static void Task1( void * pvParameters )
{

  for( ;; )
  {
    //Something here
    CalledFunction();
    //Something there
    vTaskDelay( pdMS_TO_TICKS( 1000 ) );
  }
}


int main( void )
{
  /* Create mutex here. */
  mutex = xSemaphoreCreateMutex();

  /* Create tasks and other resources. */
}
1 Like