2025-02-11 11:49 PM - last edited on 2025-02-12 01:19 AM by Andrew Neil
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
2025-02-12 01:11 AM
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 ...
2025-02-12 02:12 AM
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.