Shared memory based on multi-process concurrent-process communication

1. What is shared memory

The operating system’s implementation principle of process memory:
modern operating systems use virtual memory technology for memory management, that is, each process has its own independent virtual memory space, and the virtual memory of different processes is mapped to different physical in memory. Therefore, even if the virtual addresses in process A and process B are the same, they actually access different physical memory addresses, and the addition, deletion, checking, and modification of data do not affect each other.

The mechanism of shared memory:
it is to take out a piece of virtual address space and map it to the same physical memory. In this way, the things written by this process can be seen in another process, without copying and copying, and passing them back and forth, which greatly improves the speed of inter-process communication.

Features of shared memory:
(1) Shared memory is two-way communication (full duplex).
(2) Shared memory is the fastest among IPC communication methods. Its data transmission does not need to go through the kernel, and communicates directly on the physical memory.
(3) Shared memory does not support synchronization and mutual exclusion
(4) The life cycle of shared memory depends on the process
(5) Shared memory can be used for any number of processes and supports random access

Second, the process of shared memory

insert image description here
Let's take the process processA write and processB write as an example to describe the process of sharing memory

1. processA writes to shared memory

  • CreateFileMapping: Create a named memory-mapped file object, Windows applies for a memory area of ​​a specified size in physical memory, and returns the handle hMap of the file-mapped object;
  • MapViewOfFile: In order to be able to access this memory area, prompt Windows to map this memory space into the address space of the process;
  • Through the handle, write the information to the shared memory.

2. processB reads shared memory

  • OpenFileMapping: Open shared memory. When accessing the memory area created by processA in process processB, you must use the OpenFileMapping function to obtain the object handle hMap,
  • MapViewOfFile: Get a mapping of this memory space, so that the system maps the same memory area to the address space of this process,
  • Through the handle, copy the shared memory information to the variables of the process. (Actually, through the handle, you can already see the data in the shared memory. Whether to copy or not is a matter of business logic.)
    This achieves the purpose of shared memory.

3. Code demo

1、processA demo

  • As long as the handle of the shared memory is not closed, the process that created the shared memory is still there, and other processes can read the shared memory.
// main.cpp
#include <windows.h>
#include <iostream> 
using namespace std;

#define BUF_SIZE 4096

int main(int argc, TCHAR* argv[])
{
    
    
    // 定义共享数据
    char szBuffer[] = "Hello Shared Memory";

    // 创建共享文件句柄 
    HANDLE hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,   // 物理文件句柄
        NULL,                   // 默认安全级别
        PAGE_READWRITE,         // 可读可写
        0,                      // 高位文件大小
        BUF_SIZE,               // 地位文件大小
        "ShareMemory"           // 共享内存名称
    );

    // 映射缓存区视图 , 得到指向共享内存的指针
    LPVOID lpBase = MapViewOfFile(
        hMapFile,               // 共享内存的句柄
        FILE_MAP_ALL_ACCESS,    // 可读写许可
        0,
        0,
        BUF_SIZE
    );

    // 将数据拷贝到共享内存
    strcpy((char*)lpBase, szBuffer);
    cout << "存放入共享内存的数据:" << (char*)lpBase << endl;

    // 解除文件映射
    UnmapViewOfFile(lpBase);
    
    system("pause"); //等待其他进程读取数据

    // 关闭内存映射文件对象句柄,只要不关闭共享内存的句柄,此进程还在,其他进程就可以读取共享内存。
    //CloseHandle(hMapFile);
    return 0;
}

2、processB demo

#include <iostream>  
#include <windows.h>  
using namespace std;

#define BUF_SIZE 4096

int main()
{
    
    
    cout << "processB" << endl << endl;

    // 打开共享的文件对象
    HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, NULL, "ShareMemory");
    if (hMapFile)
    {
    
    
        LPVOID lpBase = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
        // 将共享内存数据拷贝出来
        char szBuffer[BUF_SIZE] = {
    
     0 };
        strcpy(szBuffer, (char*)lpBase);
        cout << "读取共享内存数据:" << szBuffer << endl;

        // 解除文件映射
        UnmapViewOfFile(lpBase);
        // 关闭内存映射文件对象句柄
        CloseHandle(hMapFile);
    }
    else
    {
    
    
        // 打开共享内存句柄失败
        cout << "Open Mapping Error";
    }
    system("pause");
    return 0;
}

Fourth, the problem of shared memory

Using the shared memory communication method brings new problems, that is, if multiple processes modify the same shared memory at the same time, conflicts are likely to occur. For example, if two processes write an address at the same time, the process that writes first will find that the content has been overwritten by others.
In order to prevent data confusion caused by multi-process competition for shared resources, a protection mechanism is required so that shared resources can only be accessed by one process at any time. Process synchronization is required, such as: semaphore, process lock, etc.

If there are any mistakes or deficiencies, welcome to comment and point out! Creation is not easy, please indicate the source for reprinting. If it is helpful, remember to like and follow (⊙o⊙)
For more content, please follow my personal blog: https://blog.csdn.net/qq_43148810

Guess you like

Origin blog.csdn.net/qq_43148810/article/details/130649634