Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Thread safe locale/encoding when using sprintf and printf

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):

  • is there a portable, not cumbersome way to handle these kinds of situations without resorting to custom libaries
  • if not so: what might be the reason to ommit such capability from the standard

TL;DR: How to handle multithreaded encoding (outside POSIX)?

like image 289
frhun Avatar asked Nov 19 '19 20:11

frhun


1 Answers

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.

like image 130
R.. GitHub STOP HELPING ICE Avatar answered Sep 22 '22 12:09

R.. GitHub STOP HELPING ICE