Sunday, January 28, 2024

[SOLVED] Is qputenv thread safe?

Issue

The libc documentation says that

Modifications of environment variables are not allowed in multi-threaded programs. The getenv and secure_getenv functions can be safely used in multi-threaded programs. source

In Qt5.15 the documentation for qgetenv says

The Qt environment manipulation functions are thread-safe, but this requires that the C library equivalent functions like getenv and putenv are not directly called. [...] Note: This function is thread-safe. source

However the documentation for qputenv says

Note: qputenv() was introduced because putenv() from the standard C library was deprecated in VC2005 (and later versions). qputenv() uses the replacement function in VC, and calls the standard C library's implementation on all other platforms. source

So it looks to me like, on Linux, qputenv calls putenv, which would not be thread-safe. To me, this seems to contradict the docs for qgetenv saying "The Qt environment manipulation functions are thread-safe." What am I missing? Is there a thread-safe way to set an environment variable in Qt 5.15? Thanks!


Solution

Right, qputenv and qgetenv are thread-safe insofar that they don't race each other. But nothing can make them thread-safe with a direct call to putenv, since that function and the data it manipulates just isn't thread-safe. And then qputenv isn't magically thread-safe with direct calls to getenv, either.



Answered By - Ville Voutilainen
Answer Checked By - Timothy Miller (WPSolving Admin)