5 ms·
you've gotten a lot of answers which say the same thing, but which I don't think answer your question: synchronization methods impose various complexity and pe
by fsckboy 2y ago
you've gotten a lot of answers which say the same thing, but which I don't think answer your question:
synchronization methods impose various complexity and performance penalties, and single threaded applications which don't need that would pay those penalties and get no benefit.
Unix was designed around a lightweight ethos that allowed simple combining of functions by the user on the command line. See "worse is better", but tl;dr that way of doing things proved better, and that's why you find yourself confronting what it doesn't do.
- sunshowers 2y agoWell it was better in the short term but is worse in the long term. In particular, the error handling situation is generally atrocious, which is fine for interactive/sysadmin use but much worse for serious production use.
- davidt84 2y agoThe real problem is that getenv() and setenv() were created before threads were really a thing.
- kazinator 2y agogetenv can easily be misused in a single threaded program.
- davidt84 2y agoBut it is possible to safely use it in a single threaded program. There's no way to use it safely in a multi threaded application that may use setenv (unless you add your own synchronisation, and ensure everything uses it, even third party libraries).
- kazinator 2y agoActually I don't believe that's the case. The getenv function as described by ISO C cannot be safely used in a program that only uses getenv, if that program uses ISO C threads, and more than one threat calls getenv without synchronizing with the others. I don't think POSIX fixes this: it doesn't specify that the environ array is protected against concurrent access. If two threads call getenv right around the same time, one of them could invalidate the environ array just as the other one has started to traverse it. If you want to be safe, copy the environment to a different data structure on program startup. Then have all your threads refer to that data structure.
- davidt84 2y agoHmm, I'm apparently correct for C++11, where calling getenv only is thread safe, but that's not guaranteed by earlier standards (or, as far as I can tell, by C or POSIX).
- kazinator 2y agoI'm surprised C++ would have anything to say about getenv; mostly it just includes the standard C library via normative reference.
- davidt84 2y agoNevertheless, https://en.cppreference.com/w/cpp/utility/program/getenv https://en.cppreference.com/w/cpp/utility/program/getenv
- kazinator 2y agoInteresting. So in a multi-threaded C++ program that only calls the std:: getenv function, everything is fine. If anything calls the C getenv function, like a third party library, things are maybe not fine.