I have done a test in Linux before:
Write an so, which has a global variable. In soCodeThe value of the global variable is modified at runtime. Then there are multipleProgramAnd these applications are started. At this point, it is clear that so is only loaded. When so many programs call this so, will the value of the global variable in this so be overwritten?
The answer is no. This is the answer to the test.
Now I know how it works. Although this is the practice of Windows explained in Windows via C/C ++, I think Linux is similar.
Windows uses memory map to load EXE and DLL. When an EXE/dll has multiple instances to be started, in Windows paging file (including Ram and swap files), there is only one copy of EXE and the DLL involved. This can save memory usage and improve performance.
That is to say, if it is exe, although each instance has its own address space, but when the address space is mapped to storage, they are mapped to the same place. In this case, the problem arises: What should I do with global and static variables in EXE/DLL? Each instance may modify these variables.
In Windows, copy on write protect attribute is set for the page that stores global variables and static variables. Therefore, when any thread tries to modify the content of these pages, Windows allocates a new page and modifies the address space of the thread, set the address of the newly allocated page. From then on, the thread modifies the global variable or static variable to operate on the newly allocated page. In this way, global variables or static variables will not overlap across multiple instances.
For details, refer to Windows via C/C ++ p593.