Is sprintf thread safety?

if i use sprintf,I find it’s easy to cause problems when switch thread.

sprintf is supposed to be thread-safe – of course assuming you provide separate string buffers as the first argument.

On embedded system however, implementations often and delibarately deviate from this requirement to reduce memory consumption and code size.

So to answer your question, it would be helpful to know what hardware you are using, what operating system and to see a specific case where it experience problems.

Does your thread crash after callling sprintf()? Do you have a buffer overflow that may cause that? The first rule should be to always use snprintf() to prevent that. Then is the question of what buffer you’re writing into, and when you’re printing it. printf() on embedded systems, as @manuelbl said, is not necessarily garuanteed to be threadsafe.

I use stm32f469 My problem is: folat to str have a little discipline lost part character when multiple threads run,
but it is no program when only one thread run,int long…also have no program.
Is sprintf not suitable for float in embedded platform?

thank you,the buffer is not overflow,Problem only occur when float to string. Is sprintf not suitable for float in embedded platform?

Again it depends completely on the use platform, framework and code. Do you have a minimal example to reproduce the problem? Otherwise we can only take wild guesses.

1 Like

The issue is not sprintf per se, but all calls to stdlib and which implementation of stdlib you are linking in. The STM32 platform typically links in newlib, which has issues detailed here, along with a fix. newlib and FreeRTOS

In the same article you will also find several sprintf alternatives that are more appropriate for an embedded system. I used GitHub - mpaland/printf: Tiny, fast, non-dependent and fully loaded printf implementation for embedded systems. Extensive test suite passing. and it works quite well, even with floats. Using it for logging in development is quite fine. In my case there is not a performance issue at all, in fact the UART still can’t keep up .

I’m also testing the GitHub link you sent. and i didn’t find any problems, and i found it saved function call time. Your comments prove that this library is suitable. Thank you very much.