Why can global variables in a dynamic library be used?

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.