Http://happyboy200032.blog.163.com/blog/static/469031132010713129590/
Windows creates a wall around the address space of a Win32 program. Generally, the data in the address space of a program is private and invisible to other programs. However, executing multiple execution entities means that it is no problem to share data between all execution entities of the program. When you add or delete a string in a window, this change is immediately reflected in other windows.
Between all routines, strlib shares two variables: A character array and an integer (record the number of valid strings that have been stored ). These two variables are stored in a shared special memory segment:
# Pragma data_seg ("shared ")
Int itotal = 0;
Wchar szstrings [max_strings] [max_length + 1] = {'\ 0 '};
# Pragma data_seg ()
The first # pragma describes how to create a data segment. The name here is shared. You can name this section as any name you like. Here, # All initialized variables described by Pragma are stored in the shared data segment.
The second # End Of The Pragma description section. Special initialization of variables is very important, otherwise the compiler will put them in common uninitialized data segments rather than in shared.
The connector must know that there is a shared data segment. You can directly use the DLL original code to specify the link option, as shown in the following figure:
# Pragma comment (linker, "/section: shared, RWS") the RWS letter indicates that the segment has read, write, and share attributes.
The shared memory segment allows the itotal variable and the szstrings string array to be shared among all routines of the program. Because max_strings is 256 and max_length is 63, the length of the shared memory segment is 32,772 bytes-The itotal variable requires 4 bytes, and each of the 256 pointers requires 128 bytes.
1. # pragma data_seg () is generally used in DLL. That is to say, define a shared, named data segment in the DLL. The most important thing is that the global variables in this data segment can be shared by multiple processes. Otherwise, the global variables in the DLL cannot be shared among multiple processes.
2. Shared data must be initialized. Otherwise, the Microsoft compiler will put uninitialized data in the. BSS segment, leading to failure in sharing among multiple processes.
Next, let's take a look at a practical application. We use shared data to count the number of times an application starts and process it accordingly.
At the entrance of the application:
// Control the application to be started only once
# Pragma data_seg ("flag_data ")
Int COUNT = 0;
# Pragma data_seg ()
# Pragma comment (linker, "/section: flag_data, RWS ")
If (count> 1)
{
MessageBox ("an application has been started", "warning", mb_ OK );
Return flase;
}
Count ++;