Skip to main content
Graduate
February 12, 2025
Solved

are printf, fprintf, scanf etc threadSafe in threadX?

  • February 12, 2025
  • 2 replies
  • 1239 views

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

 

 

    This topic has been closed for replies.
    Best answer by Saket_Om

    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.

    2 replies

    Graduate
    February 12, 2025

    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_OmAnswer
    Technical Moderator
    February 12, 2025

    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.

    ABasi.2Author
    Graduate
    February 12, 2025

    thank you!

    i have modified my code like this :

    int _write(int file, char *ptr, int len)
    { 
     if(tx_mutex_get(&consoleMutex,TX_WAIT_FOREVER) == TX_SUCCESS)
     {
     HAL_UART_Transmit(&huart2,(uint8_t*)ptr, len, 1000);
     tx_mutex_put(&consoleMutex);
     return len;
     }
     return 0; 
    }

    and it works fine

     

    best reguards