I have a project with tight level of clang-tidy static analysis.
In order to check some consistencies in the environment I am probing the value of a few environment variables.
int main() {
char const* ompi_size_cstr = std::getenv("OMPI_COMM_WORLD_SIZE");
...
}
(nevermind the meaning of the variable).
But now I get this warning:
/builds/user/mpi3/environment.hpp:49:51: error: function is not thread safe [concurrency-mt-unsafe,-warnings-as-errors]
const char* ompi_size_cstr = std::getenv("OMPI_COMM_WORLD_SIZE");
First, if I look at the documentation, https://en.cppreference.com/w/cpp/utility/program/getenv, it says that the function is thread-safe since C++11 (I am using C++17). But maybe the warning is referring to the fact that the environment variable itself could change behind the scenes.
Second, even if this is not thread-safe in some sense: What can I do about it? Is there a canonical solution to use getenv
?,
for example, by locking a manually introduced get_env_mtx
mutex, or perhaps making my variable declaration static
? As in,
static const char* ompi_size_cstr = std::getenv("OMPI_COMM_WORLD_SIZE");
or
static std::string ompi_size_cstr = std::getenv("OMPI_COMM_WORLD_SIZE");
Of course, I can also introduce an exception to the rule, // NOLINT(concurrency-mt-unsafe)
but I wanted to know if there is a fix that I can express as better code instead.
It would be also good to improve the code even if at the end I have to add a NOLINT
anyway.
Note: I am using clang-tidy
version 14.0.6
, and in C++17.