Discussion:
Can all environment be cached atomically?
(too old to reply)
Yuri
2024-06-14 10:26:02 UTC
Permalink
Imagine the situation when a process has multiple threads which keep
changing environment variables.

One of the threads attempts to cache all environment variables.


I am curious whether the whole environment can be cached atomically, as
it exists at some point in time, or this can't be guaranteed and some
environment variables would have to be cached at different times?


Python's os.environ object is such environment cache, which is created
when the Python interpreter is initialized.



Thanks,

Yuri




--
Posted automagically by a mail2news gateway at muc.de e.V.
Please direct questions, flames, donations, etc. to news-***@muc.de
David Chisnall
2024-06-14 11:52:53 UTC
Permalink
Imagine the situation when a process has multiple threads which keep changing environment variables.
I imagined it. It went like this:

SIGSEGV

It is undefined behaviour for two threads to change environment variables without explicit synchronisation of *all* readers and writers of environment variables. Any multithreaded program that calls `setenv` is almost certainly wrong. I would suggest that you follow these rules:

- Never call setenv.

If that can’t be done then:

- Never call setenv in a shared library and
- Never call setenv in a program after calling any function that *may* create threads.

The first rule is easier to follow.

There are *almost* not situations where calling `setenv` is the right thing to do. The only situation is where you should call it is to work around poorly designed shared libraries that provide no mechanism for communicating state to them other than environment variables. Then it’s not the right thing to do, it’s just the thing that you have to do to work around a bug.

Environment variables exist to pass state from the environment into a newly created process. Any other use is likely to be a mistake.
Python's os.environ object is such environment cache, which is created when the Python interpreter is initialized.
Almost certainly to avoid issues with concurrent writes from poorly written programs / libraries.

David

Loading...