cancel
Showing results for 
Search instead for 
Did you mean: 

are printf, fprintf, scanf etc threadSafe in threadX?

ABasi.2
Associate III

HI

i have a question about printf. fprintf,scanf etc

i'm redirecting those functions to use a UART replacing the int _write(int file, char *ptr, int len)  and int _read(int file, char *ptr, int len) functions.

 

 

int _write(int file, char *ptr, int len)
{ 
  HAL_UART_Transmit(&huart2,(uint8_t*)ptr, len, 1000); 
  return len;
}

int _read(int file, char *ptr, int len)
{    
  __HAL_UART_CLEAR_OREFLAG(&huart2);
  HAL_UART_Receive(&huart2,(uint8_t*)ptr, len,HAL_MAX_DELAY);
  HAL_UART_Transmit(&huart2,(uint8_t*)ptr,len, 1000);  
  return len;
}

 

 

 

now i'm using threadX and possibily call printf or the other function from multiple threads

is this approach already thread safe or i have to implement a mutex for the Uart?

If i have to use a mutex is that possible to get and put the mutex inside the _write or _read function or i have to get the mutex before call printf?

thank you

 

 

2 REPLIES 2
mbarg.1
Senior

I feel confused - functons make operations on data, functions are non-atomic, therefore task can interrupt execution and pass control to other task that can make changes to data, when executon is resumed, data can be changed or corrupted ...

All data must be protected before executing non atomic functions !

Unless you are 100% sure that no other function will access the same data ...

Saket_Om
ST Employee

Hello @ABasi.2 

To ensure thread safety, you need to use a mutex to protect the UART access. You can implement the mutex within the _write and _read functions, or you can acquire the mutex before calling printf or other related functions.

If your question is answered, please close this topic by clicking "Accept as Solution".

Thanks
Omar