This question is not related to something that i want to do at the moment, but something i wondered while reading the (GNU/Linux/ISO-C) Documentation for sprintf()
printf()
and setlocale()
.
The hypothetical problem:
Imagine a multithreaded application which uses printf/scanf family for user faced text output on one thread and printf/scanf for file or even network I/O on another thread. Now imagine a scenario where that application needs to use different encodings/locales for the different kinds of I/O.
The way to set the locale/encoding is to use setlocale()
which is explicitly marked as "MT-Unsafe" int the Linux Programmer's Manual.
ISO/IEC 9899:2018 has the following to say at 7.11.1.1
A call to the setlocale function may introduce a data race with other calls to the setlocale function or with calls to functions that are affected by the current locale. The implementation shall behave as if no library function calls the setlocale function.
As far as i see it, this leaves standard C with no standard way to handle the situation described prior. (that does not involve needless synchronization between threads that otherwise don't neccesairily interfere)
Note that POSIX specifies the uselocale()
function which is specifically made for this.
But this is no solution for i.e. embedded or tuly multi-platform code.
The question(s):
TL;DR: How to handle multithreaded encoding (outside POSIX)?
You cannot safely use setlocale
at all in a program once it becomes multithreaded. If you need multiple locales, you need the newlocale
/uselocale
API for thread-local or first-class locale objects, not setlocale
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With