The copy on write attribute of the Memory Page in Windows is very useful. He guarantees that if an application ProgramWhen multiple instances are started, or a DLL is used by multiple started applications at the same time, global and static variables are not contaminated.
The general principle is:
The application starts multiple instances. In the address space of these processes, part of the address space of the application corresponds to physical storage, which is a copy of memory map ). Therefore, if an instance attempts to modify a global or static variable without copy-on-write, the variable will be contaminated. Therefore, when Windows uses memory map to load applications, it recognizes global and static variables, and then sets the copy-on-write attribute to the page where these variables are stored, in this way, when an Instance tries to modify a global or static variable, A exceptin is generated. Windows captures the variable and re-allocates the page to the instance to avoid contamination. The DLL processing method is the same as this.
I think of a problem when I am working on SD today. Does the logic also exist when multiple threads in a process access global or static variables? If yes, all the functions involving global and static variables will be multithread safe! Obviously, this is impossible. The reason is:
When a thread in a process tries to modify the global or static variables, Windows allocates a new page and modifies the part of the page in the address space of the process, the physical storage of the page points to the new page. Therefore, when other threads of the Process access the variable again, the page is created. Now there is a multi-thread problem.
Therefore, copy-on-write solves the problem of multi-instance or Global static variables in DLL, which are not contaminated. It has nothing to do with multithreading. In the case of multiple threads in a process, thread synchronization is used for global and static variables to ensure thread security.