Windows shared memory c

Время на прочтение11 мин

Количество просмотров13K

Разделяемая память — самый быстрый способ обмена данными между процессами. Но в отличие от потоковых механизмов (трубы, сокеты всех мастей, файловые очереди …), здесь у программиста полная свобода действий, в результате пишут кто во что горазд.

Так и автор однажды задался мыслью, а что если … если произойдёт вырождение адресов сегментов разделяемой памяти в разных процессах. Вообще-то именно это происходит, когда процесс с разделяемой памятью делает fork, а как насчет разных процессов? Кроме того, не во всех системах есть fork.

Казалось бы, совпали адреса и что с того? Как минимум, можно пользоваться абсолютными указателями и это избавляет от кучи головной боли. Станет возможно работать со строками и контейнерами С++, сконструированными из разделяемой памяти.

Отличный, кстати, пример. Не то, чтобы автор сильно любил STL, но это возможность продемонстрировать компактный и всем понятный тест на работоспособность предлагаемой методики. Методики, позволяющей (как видится) существенно упростить и ускорить межпроцессное взаимодействие. Вот работает ли она и чем придётся заплатить, будем разбираться далее.

Введение

Идея разделяемой памяти проста и изящна — поскольку каждый процесс действует в своём виртуальном адресном пространстве, которое проецируется на общесистемное физическое, так почему бы не разрешить двум сегментам из разных процессов смотреть на одну физическую область памяти.

А с распространением 64-разрядных операционных систем и повсеместным использованием когерентного кэша, идея разделяемой памяти получила второе дыхание. Теперь это не просто циклический буфер — реализация “трубы” своими руками, а настоящий “трансфункционер континуума” — крайне загадочный и мощный прибор, причем, лишь его загадочность равна его мощи.

Рассмотрим несколько примеров использования.

  • Протокол “shared memory” при обмене данными с MS SQL. Демонстрирует некоторое улучшение производительности (~10…15%)
  • Mysql также имеет под Windows протокол “shared memory”, который улучшает производительность передачи данных на десятки процентов.
  • Sqlite размещает в разделяемой памяти индекс навигации по WAL-файлу. Причем берётся существующий файл, который отображается в память. Это позволяет использовать его процессам с разными корневыми директориями (chroot).
  • PostgreSQL использует как раз fork для порождения процессов-обработчиков запросов. Причем эти процессы наследуют разделяемую память, структура которой показана ниже.

    Фиг.1 структура разделяемой памяти PostgreSQL (отсюда)

Из общих соображений, а какой бы мы хотели видеть идеальную разделяемую память? На это легко ответить — желаем, чтобы объекты в ней можно было использовать, как если бы это были объекты, разделяемые между потоками одного процесса. Да, нужна синхронизация (а она в любом случае нужна), но в остальном — просто берёшь и используешь! Пожалуй, … это можно устроить.

Для проверки концепции требуется

минимально-осмысленная задача

:

  • есть аналог std::map<std::string, std::string>, расположенный в разделяемой памяти
  • имеем N процессов, которые асинхронно вносят/меняют значения с префиксом, соответствующим номеру процесса (ex: key_1_… для процесса номер 1)
  • в результате, конечный результат мы можем проконтролировать

Начнём с самого простого — раз у нас есть std::string и std::map, потребуется и специальный аллокатор STL.

Аллокатор STL

Допустим, для работы с разделяемой памятью существуют функции xalloc/xfree как аналоги malloc/free. В этом случае аллокатор выглядит так:

template <typename T>
class stl_buddy_alloc
{
public:
	typedef T                 value_type;
	typedef value_type*       pointer;
	typedef value_type&       reference;
	typedef const value_type* const_pointer;
	typedef const value_type& const_reference;
	typedef ptrdiff_t         difference_type;
	typedef size_t            size_type;
public:
	stl_buddy_alloc() throw()
	{	// construct default allocator (do nothing)
	}
	stl_buddy_alloc(const stl_buddy_alloc<T> &) throw()
	{	// construct by copying (do nothing)
	}
	template<class _Other>
	stl_buddy_alloc(const stl_buddy_alloc<_Other> &) throw()
	{	// construct from a related allocator (do nothing)
	}

	void deallocate(pointer _Ptr, size_type)
	{	// deallocate object at _Ptr, ignore size
		xfree(_Ptr);
	}
	pointer allocate(size_type _Count)
	{	// allocate array of _Count elements
		return (pointer)xalloc(sizeof(T) * _Count);
	}
	pointer allocate(size_type _Count, const void *)
	{	// allocate array of _Count elements, ignore hint
		return (allocate(_Count));
	}
};

Этого достаточно, чтобы подсадить на него std::map & std::string


template <typename _Kty, typename _Ty>
class q_map : 
    public std::map<
        _Kty, 
        _Ty, 
        std::less<_Kty>, 
        stl_buddy_alloc<std::pair<const _Kty, _Ty> > 
    >
{ };

typedef std::basic_string<
        char, 
        std::char_traits<char>, 
        stl_buddy_alloc<char> > q_string

Прежде чем заниматься заявленными функциями xalloc/xfree, которые работают с аллокатором поверх разделяемой памяти, стоит разобраться с самой разделяемой памятью.

Разделяемая память

Разные потоки одного процесса находятся в одном адресном пространстве, а значит каждый не thread_local указатель в любом потоке смотрит в одно и то же место. С разделяемой памятью, чтобы добиться такого эффекта приходится прилагать дополнительные усилия.

Windows

  • Создадим отображение файла в память. Разделяемая память так же как и обычная покрыта механизмом подкачки, здесь помимо всего прочего определяется, будем ли мы пользоваться общей подкачкой или выделим для этого специальный файл.
    HANDLE hMapFile = CreateFileMapping(
    	INVALID_HANDLE_VALUE,     // use paging file
    	NULL,                     // default security
    	PAGE_READWRITE,           // read/write access
    	(alloc_size >> 32)        // maximum object size (high-order DWORD)
    	(alloc_size & 0xffffffff),// maximum object size (low-order DWORD)
    	"Local\\SomeData");       // name of mapping object

    Префикс имени файла “Local\\” означает, что объект будет создан в локальном пространстве имён сессии.

  • Чтобы присоединиться к уже созданному другим процессом отображению, используем
    HANDLE hMapFile = OpenFileMapping(
    	FILE_MAP_ALL_ACCESS,      // read/write access
    	FALSE,                    // do not inherit the name
    	"Local\\SomeData");       // name of mapping object
  • Теперь необходимо создать сегмент, указывающий на готовое отображение
    void *hint = (void *)0x200000000000ll;
    unsigned char *shared_ptr = (unsigned char*)MapViewOfFileEx(
    	hMapFile,                 // handle to map object
    	FILE_MAP_ALL_ACCESS,      // read/write permission
    	0,                        // offset in map object (high-order DWORD)
    	0,                        // offset in map object (low-order DWORD)
    	0,                        // segment size,
    	hint);                    // подсказка
    

    segment size 0 означает, что будет использован размер, с которым создано отображение с учетом сдвига.

    Самое важно здесь — hint. Если он не задан (NULL), система подберет адрес на своё усмотрение. Но если значение ненулевое, будет сделана попытка создать сегмент нужного размера с нужным адресом. Именно определяя его значение одинаковым в разных процессах мы и добиваемся вырождения адресов разделяемой памяти. В 32-разрядном режиме найти большой незанятый непрерывный кусок адресного пространства непросто, в 64-разрядном же такой проблемы нет, всегда можно подобрать что-нибудь подходящее.

Linux

Здесь принципиально всё то же самое.

  • Создаём объект разделяемой памяти
      int fd = shm_open(
                     “/SomeData”,               // имя объекта, начинается с /
                     O_CREAT | O_EXCL | O_RDWR, // flags, аналогично open
                     S_IRUSR | S_IWUSR);        // mode, аналогично open
    
      ftruncate(fd, alloc_size);
    

    ftruncate в данном случае используется чтобы задать размер разделяемой памяти. Использование shm_open аналогично созданию файла в /dev/shm/. Есть еще устаревший вариант через shmget\shmat от SysV, где в качестве идентификатора объекта используется ftok (inode от реально существующего файла).

  • Чтобы присоединиться к созданной разделяемой памяти
    int fd = shm_open(“/SomeData”, O_RDWR, 0);
  • для создания сегмента
      void *hint = (void *)0x200000000000ll;
      unsigned char *shared_ptr = (unsigned char*) = mmap(
                       hint,                      // подсказка
                       alloc_size,                // segment size,
                       PROT_READ | PROT_WRITE,    // protection flags
                       MAP_SHARED,                // sharing flags
                       fd,                        // handle to map object
                       0);                        // offset
    

    Здесь также важен hint.

Ограничения на подсказку

Что касается подсказки (hint), каковы ограничения на её значение? Вообще-то, есть разные виды ограничений.

Во-первых, архитектурные/аппаратные. Здесь следует сказать несколько слов о том, как виртуальный адрес превращается в физический. При промахе в кэше TLB, приходится обращаться в древовидную структуру под названием “таблица страниц” (page table). Например, в IA-32 это выглядит так:

Фиг.2 случай 4K страниц, взято здесь

Входом в дерево является содержимое регистра CR3, индексы в страницах разных уровней — фрагменты виртуального адреса. В данном случае 32 разряда превращаются в 32 разряда, всё честно.

В AMD64 картина выглядит немного по-другому.

Фиг.3 AMD64, 4K страницы, взято отсюда

В CR3 теперь 40 значимых разрядов вместо 20 ранее, в дереве 4 уровня страниц, физический адрес ограничен 52 разрядами при том, что виртуальный адрес ограничен 48 разрядами.

И лишь в(начиная с) микроархитектуре Ice Lake(Intel) дозволено использовать 57 разрядов виртуального адреса (и по-прежнему 52 физического) при работе с 5-уровневой таблицей страниц.

До сих пор мы говорили лишь об Intel/AMD. Просто для разнообразия, в архитектуре Aarch64 таблица страниц может быть 3 или 4 уровневой, разрешая использование 39 или 48 разрядов в виртуальном адресе соответственно (1).

Во вторых, программные ограничения. Microsoft, в частности, налагает (44 разряда до 8.1/Server12, 48 начиная с) таковые на разные варианты ОС исходя из, в том числе, маркетинговых соображений.

Между прочим, 48 разрядов, это 65 тысяч раз по 4Гб, пожалуй, на таких просторах всегда найдётся уголок, куда можно приткнуться со своим hint-ом.

Аллокатор разделяемой памяти

Во первых. Аллокатор должен жить на выделенной разделяемой памяти, размещая все свои внутренние данные там же.

Во вторых. Мы говорим о средстве межпроцессного общения, любые оптимизации, связанные с использованием TLS неуместны.

В третьих. Раз задействовано несколько процессов, сам аллокатор может жить очень долго, особую важность принимает уменьшение внешней фрагментации памяти.

В четвертых. Обращения к ОС за дополнительной памятью недопустимы. Так, dlmalloc, например, выделяет фрагменты относительно большого размера непосредственно через mmap. Да, его можно отучить, завысив порог, но тем не менее.

В пятых. Стандартные внутрипроцессные средства синхронизации не годятся, требуются либо глобальные с соответствующими издержками, либо что-то, расположенное непосредственно в разделяемой памяти, например, спинлоки. Скажем спасибо когерентному кэшу. В posix на этот случай есть еще безымянные разделяемые семафоры.

Итого, учитывая всё вышесказанное а так же потому, что под рукой оказался живой аллокатор методом близнецов (любезно предоставленный Александром Артюшиным, слегка переработанный), выбор оказался несложным.

Описание деталей реализации оставим до лучших времён, сейчас интересен публичный интерфейс:

class BuddyAllocator {
public:
	BuddyAllocator(uint64_t maxCapacity, u_char * buf, uint64_t bufsize);
	~BuddyAllocator(){};

	void *allocBlock(uint64_t nbytes);
	void freeBlock(void *ptr);
...
};

Деструктор тривиальный т.к. никаких посторонних ресурсов BuddyAllocator не захватывает.

Последние приготовления

Раз всё размещено в разделяемой памяти, у этой памяти должен быть заголовок. Для нашего теста этот заголовок выглядит так:

struct glob_header_t {
	// каждый знает что такое magic
	uint64_t magic_;
	// hint для присоединения к разделяемой памяти
	const void *own_addr_;
	// собственно аллокатор
	BuddyAllocator alloc_;
	// спинлок
	std::atomic_flag lock_;
	// контейнер для тестирования
	q_map<q_string, q_string> q_map_;

	static const size_t alloc_shift = 0x01000000;
	static const size_t balloc_size = 0x10000000;
	static const size_t alloc_size = balloc_size + alloc_shift;
	static glob_header_t *pglob_;
};
static_assert (
    sizeof(glob_header_t) < glob_header_t::alloc_shift, 
    "glob_header_t size mismatch");

glob_header_t *glob_header_t::pglob_ = NULL;

  • own_addr_ прописывается при создании разделяемой памяти для того, чтобы все, кто присоединяются к ней по имени могли узнать фактический адрес (hint) и пере-подключиться при необходимости
  • вот так хардкодить размеры нехорошо, но для тестов приемлемо
  • вызывать конструктор(ы) должен процесс, создающий разделяемую память, выглядит это так:
    glob_header_t::pglob_ = (glob_header_t *)shared_ptr;
    
    new (&glob_header_t::pglob_->alloc_)
            qz::BuddyAllocator(
                    // максимальный размер
                    glob_header_t::balloc_size,
                    // стартовый указатель
                    shared_ptr + glob_header_t::alloc_shift,
                    // размер доступной памяти
                    glob_header_t::alloc_size - glob_header_t::alloc_shift;
    
    new (&glob_header_t::pglob_->q_map_) 
                    q_map<q_string, q_string>();
    
    glob_header_t::pglob_->lock_.clear();
    
  • подключающийся к разделяемой памяти процесс получает всё в готовом виде
  • теперь у нас есть всё что нужно для тестов кроме функций xalloc/xfree
    void *xalloc(size_t size)
    {
    	return glob_header_t::pglob_->alloc_.allocBlock(size);
    }
    void xfree(void* ptr)
    {
    	glob_header_t::pglob_->alloc_.freeBlock(ptr);
    }
    

Похоже, можно начинать.

Эксперимент

Сам тест очень прост:

for (int i = 0; i < 100000000; i++)
{
        char buf1[64];
        sprintf(buf1, "key_%d_%d", curid, (i % 100) + 1);
        char buf2[64];
        sprintf(buf2, "val_%d", i + 1);

        LOCK();

        qmap.erase(buf1); // пусть аллокатор трудится
        qmap[buf1] = buf2;

        UNLOCK();
}

Curid — это номер процесса/потока, процесс, создавший разделяемую память имеет нулевой curid, но для теста это неважно.
Qmap, LOCK/UNLOCK для разных тестов разные.

Проведем несколько тестов

  1. THR_MTX — многопоточное приложение, синхронизация идёт через std::recursive_mutex,
    qmap — глобальная std::map<std::string, std::string>
  2. THR_SPN — многопоточное приложение, синхронизация идёт через спинлок:
    std::atomic_flag slock;
    ..
    while (slock.test_and_set(std::memory_order_acquire));  // acquire lock
    …
    slock.clear(std::memory_order_release);                 // release lock

    qmap — глобальная std::map<std::string, std::string>

  3. PRC_SPN — несколько работающих процессов, синхронизация идёт через спинлок:
    while (glob_header_t::pglob_->lock_.test_and_set(              // acquire lock
            std::memory_order_acquire));                          
    …
    glob_header_t::pglob_->lock_.clear(std::memory_order_release); // release lock

    qmapglob_header_t::pglob_->q_map_

  4. PRC_MTX — несколько работающих процессов, синхронизация идёт через именованный мутекс.

    qmapglob_header_t::pglob_->q_map_

Результаты (тип теста vs. число процессов\потоков):

Эксперимент проводился на двухпроцессорном (48 ядер) компьютере с Xeon® Gold 5118 2.3GHz, Windows Server 2016.

Итого

  • Да, использовать объекты/контейнеры STL (размещенные в разделяемой памяти) из разных процессов можно при условии, что они сконструированы надлежащим образом.
  • По производительности явного проигрыша нет, скорее наоборот, PRC_SPN даже чуть быстрее THR_SPN. Поскольку разница здесь только в аллокаторе, значит BuddyAllocator чуть быстрее malloc\free от MS (при невысокой конкуренции).
  • Проблемой является высокая конкуренция. Даже самый быстрый вариант — многопоточность + std::mutex в этих условиях работает безобразно медленно. Здесь были бы полезны lock-free контейнеры, но это уже тема для отдельного разговора.

Вдогонку

Разделяемую память часто используют для передачи больших потоков данных в качестве своеобразной “трубы”, сделанной своими руками. Это отличная идея даже несмотря на необходимость устраивать дорогостоящую синхронизацию между процессами. То, что она не дешевая, мы видели на тесте PRC_MTX, когда работа даже без конкуренции, внутри одного процесса ухудшила производительность в разы.

Объяснение дороговизны простое, если std::(recursive_)mutex (критическая секция под windows) умеет работать как спинлок, то именованный мутекс — это системный вызов, вход в режим ядра с соответствующими издержками. Кроме того, потеря потоком/процессом контекста исполнения это всегда очень дорого.

Но раз синхронизация процессов неизбежна, как же нам уменьшить издержки? Ответ давно придуман — буферизация. Синхронизируется не каждый отдельный пакет, а некоторый объем данных — буфер, в который эти данные сериализуются. Если буфер заметно больше размера пакета, то и синхронизироваться приходится заметно реже.

Удобно смешивать две техники — данные в разделяемой памяти, а через межпроцессный канал данных (ex: петля через localhost) отправляют только относительные указатели (от начала разделяемой памяти). Т.к. указатель обычно меньше пакета данных, удаётся сэкономить на синхронизации.

А в случае, когда разным процессам доступна разделяемая память по одному виртуальному адресу, можно еще немного добавить производительности.

  • не сериализуем данные для отправки, не десериализуем при получении
  • отправляем через поток честные указатели на объекты, созданные в разделяемой памяти
  • при получении готового (указателя) объекта, пользуемся им, затем удаляем через обычный delete, вся память автоматически освобождается. Это избавляет нас от возни с кольцевым буфером
  • можно даже посылать не указатель, а (минимально возможное — байт со значением “you have mail”) уведомление о факте наличия чего-нибудь в очереди

Напоследок

Чего нельзя делать с объектами, сконструированными в разделяемой памяти.

  1. Использовать RTTI. По понятным причинам. Std::type_info объекта существует вне разделяемой памяти и недоступен в разных процессах.
  2. Использовать виртуальные методы. По той же причине. Таблицы виртуальных функций и сами функции недоступны в разных процессах.
  3. Если говорить об STL, все исполняемые файлы процессов, разделяющих память, должны быть скомпилированы одним компилятором с одними настройками да и сама STL должна быть одинаковой.

PS: спасибо Александру Артюшину и Дмитрию Иптышеву (Dmitria) за помощь в подготовке данной статьи.

UPD:

исходники BuddyAllocator выложены здесь под BSD лицензией.

target

I want to know how to communicate between processes.I am here Interprocess Communication (IPC) Introduction — ZH Cheese — Blog Park I saw a variety of methods of interprocess communication, among which it mentioned that shared memory is the fastest way, so I want to practice it.

The goal of this article is to achieve the test of writing data to a shared memory in one process and reading data from that shared memory in another process.

On Windows, the most authoritative examples of documentation and code are: <Creating Named Shared Memory — Win32 apps | Microsoft Docs>
In addition, Sample Windows Shared Memory — Funny Mania — Blog Park This also helped me a lot.

Introduction to using functions

The function used requires #include <windows.h>.The functions associated with Shared Memory and the parameters to be aware of are discussed below:

CreateFileMapping

First, use the CreateFileMapping Create a file mapping object.

HANDLE CreateFileMappingA(
  HANDLE                hFile,
  LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
  DWORD                 flProtect,
  DWORD                 dwMaximumSizeHigh,
  DWORD                 dwMaximumSizeLow,
  LPCSTR                lpName
);

Where:

  • The hFile parameter will be set to INVALID_HANDLE_VALUE

If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a size for the file mapping object in the dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMapping creates a file mapping object of a specified size that is backed by the system paging file instead of by a file in the file system.

  • flProtect represents a protected permission, such as PAGE_READWRITE stands for read and write permissions.
  • lpName will be the name of the File.Of course, the name should be the same in both of my testing processes.
OpenFileMapping

In the process of reading memory, the OpenFileMapping Open a file mapping object.

HANDLE OpenFileMappingA(
  DWORD  dwDesiredAccess,
  BOOL   bInheritHandle,
  LPCSTR lpName
);

Where:

  • dwDesiredAccess represents permissions, such as FILE_MAP_ALL_ACCESS means that all permissions include read and write.
  • bInheritHandle:

If this parameter is TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the handle cannot be inherited.

  • lpName will be the name of the File.Of course, the name should be the same in both of my testing processes.
MapViewOfFile

Use MapViewOfFile Handle s returned by CreateFileMapping or OpenFileMapping can be mapped to a cache.

LPVOID MapViewOfFile(
  HANDLE hFileMappingObject,
  DWORD  dwDesiredAccess,
  DWORD  dwFileOffsetHigh,
  DWORD  dwFileOffsetLow,
  SIZE_T dwNumberOfBytesToMap
);
  • hFileMappingObject: Fill in the Handle of the file mapping object returned by CreateFileMapping or OpenFileMapping.
  • dwDesiredAccess: Represents permissions, such as FILE_MAP_ALL_ACCESS stands for read and write permissions.
  • dwNumberOfBytesToMap: How many bytes are mapped.(If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping.)

Code Practice

Processes for writing data to shared memory:

#include <windows.h>
#include <iostream>

//Data structure for testing
struct MyTestData
{
    int TestInt;        //Integer data for testing
    char TestStr[5];    //String data for testing
};

int main()
{
    //Name of FMO(file mapping object) (should be consistent between the two test processes)
    const std::wstring FMO_Name(L"TestFMO");   

    //Create an FMO
    HANDLE hMap = CreateFileMapping(
        INVALID_HANDLE_VALUE,       // use paging file
        NULL,                       // default security
        PAGE_READWRITE,             // read-write permission
        0,                          // maximum object size (high-order DWORD)
        sizeof(MyTestData),         // maximum object size (low-order DWORD)
        FMO_Name.c_str());          // Name of FMO

    //Map to Buffer
    void* pBuffer = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    
    //Convert pointer to MyTestData type
    MyTestData* shared_data = (MyTestData*)pBuffer;


    //Changing data in a loop
    while (1)
    {
        //Write a random data
        shared_data->TestInt = rand() % 10;
        for (int i = 0; i < 4; i++)
            shared_data->TestStr[i] = 'a' + rand() % 26;
        shared_data->TestStr[4] = '\0';

        //Print information:
        std::cout << "Write to shared memory:" << shared_data->TestInt <<' '<< shared_data->TestStr <<std::endl;

        //Stay for 1 second
        Sleep(1000);
    }


    //Unmap
    UnmapViewOfFile(pBuffer);
    //Turn off FMO's Handle
    CloseHandle(hMap);
    
    return 0;
}

Process for reading data from shared memory:

#include <windows.h>
#include <iostream>

//Data structure for testing
struct MyTestData
{
    int TestInt;        //Integer data for testing
    char TestStr[5];    //String data for testing
};

int main()
{
    //Name of FMO(file mapping object) (should be consistent between the two test processes)
    const std::wstring FMO_Name(L"TestFMO");

    //Open an FMO
    HANDLE hMap = OpenFileMapping(
        FILE_MAP_ALL_ACCESS,    // Read/Write Permissions
        FALSE,                  // do not inherit the name
        FMO_Name.c_str());      // Name of FMO


    //Map to Buffer
    void* pBuffer = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);

    //Convert pointer to MyTestData type
    MyTestData* shared_data = (MyTestData*)pBuffer;


    //Reading data continuously in a loop
    while (1)
    {
        //Print information:
        std::cout << "Read shared memory:" << shared_data->TestInt << ' ' << shared_data->TestStr << std::endl;
        
        //Stay for 0.1 seconds
        Sleep(100);
    }


    //Unmap
    UnmapViewOfFile(pBuffer);
    //Turn off FMO's Handle
    CloseHandle(hMap);

    return 0;
}

Effect:

*Another test

I was wondering if there was a pointer in shared memory that pointed to a data in process A, could process B still be accessed this way?
Unfortunately, test discovery is not possible.

Reading in another process reveals that there may be multiple behaviors:

or

There was another uninterrupted time, but the data read «hot.»I tried several times and couldn’t reproduce them

Posted by zhengsheng2010
at Nov 19, 2020 — 2:32 AM
Tag:
Windows

Эта статья является переводом документации кроссплатформенной библиотеки shmem. Статья переводилась на автомате поздно ночью, поэтому иногда путаются понятия хранилища (storage) и разделяемой памяти (shared memory), что в контексте статьи одно и то же. Поправлю на досуге:) Эта библиотека (а также многие другие) связаны с именем Константина Книжника, а ссылки на сайты, где размещены материалы, почему-то ломаются. Так что если ссылка не работает, то стоит Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript. и поискать в поисковике e-mail разработчика библиотеки: Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.. Этим способом я его и нашел:)

Описание


Класс shared_memory предоставляет эффективный платформонезависимый интерфейс для разделяемой памяти. Этот класс дает возможность нескольким приложениям получать доступ к разделяемой памяти. Этот класс предоставляет методы для создания/освобождения объектов в разделяемой памяти, установку исключительной или общей блокировки. Блокировки могут быть вложенными и могут быть использованы для синхронизации доступа к разделяемым объектам различными потоками внутри процесса, а также различными процессами.

Основная идея этого класса это поддержка эффективного механизма межпроцессного обмена данными и разделение данных. Было сделано предположение, что большую часть времени нет конфликта доступа к данным между конкурирующими процессами. Так что класс shared_memory был разработан  для оптимизации такого случая: блокировка объекта процессом без ожидания. Использование специальных атомарных инструкций процессора i486 (или выше) XADD и CMPXCHG позволяет избежать переключения контекста для блокировки ресурса, который не блокирован другим процессом. Классом shared_memory поддерживаются только блокировки памяти. Так что блокировка различных объектов невозможна.

Возможно отобразить секцию разделяемой памяти в файл и использовать ее как постоянное хранилище для объектов. Транзакции не поддерживаются этим классом. Если вашему приложению требуется атомарность и отказоустойчивость, смотрите Generic Object Oriented Database System или Persistent Object Storage for C++.

Так как объекты, размещенные в разделяемой памяти могут содержать ссылки на другие объекты в разделяемой памяти, необходимо гарантировать, что секция разделяемой памяти отображена в тот же диапазон виртуальных адресов во всех приложениях, использующих эту секцию. Этот адрес может быть указан в методе open() или, если не указан, определен системой. Когда секция отображается в адресное пространство другого процесса, метод open() пытается отобразить секцию на такой же виртуальный адрес. Если это невозможно ( например, если какая-либо другая секция отображена на тот же диапазон адресов), тогда open() завершается с ошибкой (POST++ позволяет перемещать секцию и регулировать ссылки, но это возможно только когда секция используется только одним приложением).

Размещение объектов в разделяемой памяти производится алгоритмом с использованием списка свободных ячеек памяти с перемещаемым указателем текущей позиции в списке. Два дополнительных слова выделяются перед объектом и после него, делая возможным эффективное слияние последующих ячеек во время операции free() (постоянное время освобождения объектов). После создания, секция разделяемой памяти не может быть увеличена. Максимальный размер секции должен быть определен в параметрах  open().

Интерфейс


static shared_memory* find_storage(void* obj);

Получая указатель на объект, этот статический метод возвращает указатель на секцию разделяемой памяти, к которой принадлежит этот объект. Если объект не размещен классом shared_memory или секция уже закрыта, этот метод возвращает NULL.

status lock(lock_descriptor& lck, unsigned msec = INFINITE);

Блокирует память как в общем, так и в исключительном режиме. Режим блокировки указывается через объект lock_descriptor, предоставляемый приложением. Этот объект не должен быть удален до вызова метода unlock() для этого дескриптора блокировки. Блокировки могут быть вложенными, так что вызов метода lock() дважды требует двух вызовов unlock() для отмены блокировки памяти. Ошибочным является использование одного дескриптора блокировки для более, чем одного запроса блокировки.

Необязательный параметр msec определяет значение таймаута ожидания удовлетворения запроса блокировки. Если таймаут истечет до предоставления блокировки, метод lock() вернет код ошибки shared_memory::timeout_expired. Если msec установлено в 0, lock() завершится незамедлительно, если блокировка невозможна. Смотрите Удобный механизм блокировки для альтернативного пути установки блокировок.

Использование блокировок может вызвать проблему взаимной блокировки. Рассмотрим следующую ситуацию: приложения A и B блокируют память в общем режиме, затем оба пытаются обновить свою блокировку до исключительной. Но обе эти блокировки не могут быть предоставлены по причине общей блокировки другого приложения. Так что эти приложения не могут продолжить выполнение и будут ждать друг друга. Для избежания взаимных блокировок, вы должны использовать обновления блокировок с осторожностью и, если вы знаете, что метод разделяемого объекта, который не изменяет объект, может вызвать может вызвать другой метод, который изменяет объект, лучше использовать исключительную блокировку в первом методе.

status unlock(lock_descriptor& lck);

Снимает блокировку, предварительно установленную  методом lock(). Блокировки могут быть вложенными, так что вызов метода unlock() не будет необходимым для разблокировки памяти. Дескриптор блокировки, передаваемый в метод unlock() должен быть тем же объектом, что был передан в lock().

void* allocate(size_t size, bool initialize_by_zero = true);

Размещение объектов в секции разделяемой памяти. Если нет достаточного пространства для размещения нового объекта, возвращается NULL. Если второй параметр initialize_by_zero установлен в true, то объект инициализируется нулями.

void free(void* ptr);

Освобождает указанный объект. Файл может быть усечен в результате освобождения объектов в его конце.

static void deallocate(void* obj);

Этот метод делает то же, что и предыдущий, но может вызываться без указателя на объект shared_memory. Этот метод вызывает метод find_storage(), чтобы найти пространство, в котором размещен объект, а затем освобождает память объекта методом free().

status open(const char* file_name, const char* shared_name, size_t max_size, open_mode mode = read_write, void* desired_address = NULL);

Создает или открывает  секцию разделяемой памяти. Параметр shared_name определяет системное имя объекта и не должно конфликтовать с именами других объектов системы (события, семафоры, мьютексы,…). Точнее, shared_name используется для генерации набора идентификаторов, которые присваиваются объектам синхронизации, используемым классом shared_memory и самим объектом отображения файла. Эти идентификаторы создаются из  shared_name, дополненным десятичным числом (1,2,…).

Если параметр file_name не равен NULL, секция памяти отображается в файл, позволяя сохранять данные между сессиями. Если параметр file_name равен NULL, создается анонимный объект отображения памяти с памятью, выделенной из файла подкачки.

Параметр max_size определяет размер создаваемой секции памяти. Этот параметр вызывается в первый раз для создания объекта разделяемой памяти. Все последующие вызовы open() другими процессами открывают существующий объект и не могут изменить его размер. Если размер отображаемого файла больше, чем max_size, то размер создаваемой секции устанавливается равным размеру файла (он не может быть расширен в этом случае). Если max_size больше, чем размер файла, тогда Windows сначала расширит файл до размера объекта отображаемой памяти. Файл будет усечен до актуального размера использованием размера метода close() (но необходимо иметь достаточно свободного пространства на диске для хранения всех max_size байт отображаемого файла).

Параметр mode может быть использован для выбора режима доступа read_only или read_write для секции памяти. В обоих случаях файл открывается для чтения и записи и создается объекта памяти с полными правами доступа. Но при использовании режима read_only, секция отображается на виртуальную память с правами доступа только для чтения. Так что любая попытка модифицировать объект в секции, открытой в режиме только для чтения, приведет к нарушению доступа (access violation).

Если параметр desired_address не ноль, секция будет отображаться на указанный виртуальный адрес. В противном случае, система сама найдет подходящий адрес. Для сохранения корректных ссылок между разделенными объектами, необходимо отображать секцию памяти  на такой же виртуальный адрес в каждом приложении. Так как приложение может отображать другие объекты отображения памяти, этот адрес может быть уже занят. Чтобы избежать такого конфликта, вы можете явно указать адрес, по которому секция должна отображаться. Если только один объект отображения памяти используется во всех приложениях или размеры этих объектов и порядок их создания одинаков во всех приложениях, система может выбрать адрес сама.

status flush();

Сбрасывает измененные страницы на диск. Этот метод имеет смысл только если используется отображение в файл.

void close();

Этот метод закрывает хранилище. Если больше нет процессов, использующих этот объект разделяемой памяти, то он должен быть освобожден. Если секция разделяемой памяти отображена в файл, то перед освобождением все измененные страницы сохраняются на диск и затем файл усекается до его действительного размера (используемого размещенными объектами).

char* get_error_text(status code, char* buf, size_t buf_size) const;

Получая код статуса, возвращаемый методом shared_memory, этот метод копирует в предоставляемый буфер текст сообщения для этого кода.

void set_root_object(void* root);

Этот метод хранит указатель на корневой (root) объект. Ссылка на корневой объект может быть получена использованием метода get_root_object() в следующих сессиях (конечно, если разделяемая секция отображена в файл). Все другие объекты из памяти могут быть доступны через обычные указатели из корневого объекта.

Обычно создание корневого объекта происходит в момент создания хранилища (но root можно изменить в любой момент). Не забывайте про исключительную блокировку базы данных во время инициализации хранилища, если несколько процессов могут одновременно пытаться открыть хранилище.

void* get_root_object() const;

Извлекает ссылку на корневой объект хранилища. Эта ссылка должна быть предварительно  сохранена через set_root_object(void* root).

void check_heap();

Проверяет содержимое кучи (heap) разделяемых объектов. Эта функция выполняется для всех объектов и свободных участков в секции разделяемой памяти и проверяет смещение полей до и после каждого сегмента. Выражение assert проверяет, что значения этих полей последовательны. Непоследовательность кучи может быть вызвана подвижным указателем, записью в массив элемента со значением индекса, выходящим за границы массива, или в результате краха системы (программы). Этот метод должен быть вызван с блокировкой хранилища в общем или исключительном режиме.

 Удобный механизм блокировки


 При использовании методов lock()/unlock() вы должны сохранять баланс вызовов lock/unlock и создавать объекты дескрипторов блокировки. Но обычно блокировки используются структурным образом, защищая блоки кода программы. Есть два класса, которые помогают избежать написания дополнительного кода и снизить вероятность возникновения ошибок: exclusive_lock и shared_lock. Эти классы устанавливают блокировку в конструкторе и снимают блокировку в деструкторе. Так что, если вы хотите защитить блок кода, единственное, что вы должны сделать — создать локальный (автоматический) объект классов exclusive_lock или shared_lock в стеке. Компилятор сделает всю остальную работа за вас, вызывая конструктор перед входом в блок и деструктор после выхода их него. Смотрите пример в шаблоне приложения.

Примитивы синхронизации


В дополнение к механизму блокировки хранилища, имеются два примитива синхронизации: семафор (semaphore) и событие (event). Эти классы, определенные в shmem.h, предоставляют платформонезависимый интерфейс для операций синхронизации. Таблица ниже содержит описание методов этих классов:

семафор:

Метод Описание
 open  Создает семафор с указанным глобальным именем и устанавливает  его значение в init_value. Если name равно NULL, семафор будет локальным внутри процесса.  Метод возвращает false, если семафор не может быть создан.
 wait  Ожидает определенный период времени, пока значение семафора не станет отличным от нуля. Метод возвращает false, если таймаут истек и true в противном случае.
 signal  Увеличивает семафор на inc
 close  Закрывает семафор (в Unix этот метод не делает ничего)

событие:

Метод Описание
 open  Создает событие с указанным глобальным именем и устанавливает состояние из параметра signaled. Если name равно NULL, событие является локальным внутри процесса. Метод возвращает false, если событие не может быть создано.
 wait  Ожидает определенный период времени, пока событие не сигнализирует. Метод возвращает false, если таймаут истек прежде, чем событие переключилось в сигнализирующее состояние, и true в противном случае.
 signal  Устанавливает состояние события в сигнализирующее.
 reset  Сбрасывает состояние события в несигнализирующее.
 close  Закрывает событие (в Unix этот метод не делает ничего).

Основанные (based) указатели


Использование квалификатора __based(), поддерживаемого компилятором Microsoft Visual C++, делает возможность отображать секцию разделяемой памяти на различные виртуальные адреса в различных приложениях. Статический указатель используется для указания на начало отображаемой секции (так что в каждый момент времени только одна секция может быть отображена). Для использования этой схемы, вы должны объявить все поля, являющимися ссылками, разделяемых объектов с помощью макроса REF(type) вместо TYPE* и компилировать ваше приложение с опцией -DUSE_BASED_POINTERS.

Шаблон приложения


shared_memory shmem;
class tree { 
  public:
    tree* left;
    tree* right;
    int   val;

    void* operator new(size_t size) { 
	return shmem.alloc(size);
    }
    void operator delete(void* p) { 
	shmem.free(p);
    }
    tree(int key) { val = key; left = right = NULL; }
};

class root_object { 
  public:
    tree* root;

    void  insert(int key) { 
	exclusive_lock x_lock(shmem);
	...
    }
    tree* search(int key) { 
	shared_lock s_lock(shmem); 
	...
    }
    void  remove(int key) { 
	exclusive_lock x_lock(shmem);
	...
    }
    void* operator new(size_t size) { 
	return shmem.alloc(size);
    }
    void operator delete(void* p) { 
	shmem.free(p);
    }
    root_object() { root = NULL; }
};

main()
{
    shared_memory::status rc;
    root_object* root;
    rc = shmem.open("test.odb", "test", max_size);
    if (rc != shared_memory::ok) { 
	shmem.get_error_text(rc, buf, sizeof buf);
	fprintf(stderr, "Field to open file: %s\n", buf);
	return EXIT_FAILURE;
    } else { 
	exclusive_lock x_lock(shmem);
	root = (root_object*)shmem.get_root_object();
	if (root == NULL) { 
	    root = new root_object;
	    shmem.set_root_object(root);
	}
    }
    root->insert(0);
    ...
    shmem.close();
    return EXIT_SUCCESS;
}

Shared memory is typically the fastest form of interprocess communication. It provides a memory area that is shared between processes. One process can write data to the area and another process can read it.

In Boost.Interprocess the class boost::interprocess::shared_memory_object is used to represent shared memory. Include the header file boost/interprocess/shared_memory_object.hpp to use this class.

Example 33.1. Creating shared memory

#include <boost/interprocess/shared_memory_object.hpp>
#include <iostream>

using namespace boost::interprocess;

int main()
{
  shared_memory_object shdmem{open_or_create, "Boost", read_write};
  shdmem.truncate(1024);
  std::cout << shdmem.get_name() << '\n';
  offset_t size;
  if (shdmem.get_size(size))
    std::cout << size << '\n';
}

The constructor of boost::interprocess::shared_memory_object expects three parameters. The first parameter specifies whether the shared memory should be created or just opened. Example 33.1 handles both cases. boost::interprocess::open_or_create will open shared memory if it already exists or create shared memory if it doesn’t.

Opening existing shared memory assumes that it has been created before. To uniquely identify shared memory, a name is assigned. That name is specified by the second parameter passed to the constructor of boost::interprocess::shared_memory_object.

The third parameter determines how a process can access shared memory. In Example 33.1, boost::interprocess::read_write says the process has read-write access.

After creating an object of type boost::interprocess::shared_memory_object, a corresponding shared memory block will exist within the operating system. The size of this memory area is initially 0. To use the area, call truncate(), passing in the size of the shared memory in bytes. In Example 33.1, the shared memory provides space for 1,024 bytes. truncate() can only be called if the shared memory has been opened with boost::interprocess::read_write. If not, an exception of type boost::interprocess::interprocess_exception is thrown. truncate() can be called repeatedly to adjust the size of the shared memory.

After creating shared memory, member functions such as get_name() and get_size() can be used to query the name and the size of the shared memory.

Because shared memory is used to exchange data between different processes, each process needs to map the shared memory into its address space. The class boost::interprocess::mapped_region is used to do this. It may come as a surprise that two classes (boost::interprocess::shared_memory_object and boost::interprocess::mapped_region) are needed to access shared memory. This is done so that the class boost::interprocess::mapped_region can also be used to map other objects into the address space of a process.

Example 33.2. Mapping shared memory into the address space of a process

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>

using namespace boost::interprocess;

int main()
{
  shared_memory_object shdmem{open_or_create, "Boost", read_write};
  shdmem.truncate(1024);
  mapped_region region{shdmem, read_write};
  std::cout << std::hex << region.get_address() << '\n';
  std::cout << std::dec << region.get_size() << '\n';
  mapped_region region2{shdmem, read_only};
  std::cout << std::hex << region2.get_address() << '\n';
  std::cout << std::dec << region2.get_size() << '\n';
}

To use the class boost::interprocess::mapped_region, include the header file boost/interprocess/mapped_region.hpp. An object of type boost::interprocess::shared_memory_object must be passed as the first parameter to the constructor of boost::interprocess::mapped_region. The second parameter determines whether access to the memory area is read-only or read-write.

Example 33.2 creates two objects of type boost::interprocess::mapped_region. The shared memory named Boost is mapped twice into the address space of the process. The address and the size of the mapped memory area is written to standard output using the member functions get_address() and get_size(). get_size() returns 1024 in both cases, but the return value of get_address() is different for each object.

Note

Example 33.2, and some of the examples that follow, will cause a compiler error with Visual C++ 2013 and Boost 1.55.0. The bug is described in ticket 9332. This bug has been fixed in Boost 1.56.0.

Example 33.3. Writing and reading a number in shared memory

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>

using namespace boost::interprocess;

int main()
{
  shared_memory_object shdmem{open_or_create, "Boost", read_write};
  shdmem.truncate(1024);
  mapped_region region{shdmem, read_write};
  int *i1 = static_cast<int*>(region.get_address());
  *i1 = 99;
  mapped_region region2{shdmem, read_only};
  int *i2 = static_cast<int*>(region2.get_address());
  std::cout << *i2 << '\n';
}

Example 33.3 uses the mapped memory area to write and read a number. region writes the number 99 to the beginning of the shared memory. region2 then reads the same location in shared memory and writes the number to the standard output stream. Even though region and region2 represent different memory areas within the process, as seen by the return values of get_address() in the previous example, the program prints 99 because both memory areas access the same underlying shared memory.

Example 33.4. Deleting shared memory

#include <boost/interprocess/shared_memory_object.hpp>
#include <iostream>

using namespace boost::interprocess;

int main()
{
  bool removed = shared_memory_object::remove("Boost");
  std::cout << std::boolalpha << removed << '\n';
}

To delete shared memory, boost::interprocess::shared_memory_object offers the static member function remove(), which takes the name of the shared memory to be deleted as a parameter (see Example 33.4).

Boost.Interprocess partially supports the RAII idiom through a class called boost::interprocess::remove_shared_memory_on_destroy. Its constructor expects the name of an existing shared memory. If an object of this class is destroyed, the shared memory is automatically deleted in the destructor.

The constructor of boost::interprocess::remove_shared_memory_on_destroy does not create or open the shared memory. Therefore, this class is not a typical representative of the RAII idiom.

If remove() is never called, the shared memory continues to exist even if the program terminates. Whether or not the shared memory is automatically deleted depends on the underlying operating system. Windows and many Unix operating systems, including Linux, automatically delete shared memory once the system is restarted.

Windows provides a special kind of shared memory that is automatically deleted once the last process using it has been terminated. Access the class boost::interprocess::windows_shared_memory, which is defined in boost/interprocess/windows_shared_memory.hpp, to use this kind of shared memory (see Example 33.5).

Example 33.5. Using Windows-specific shared memory

#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>

using namespace boost::interprocess;

int main()
{
  windows_shared_memory shdmem{open_or_create, "Boost", read_write, 1024};
  mapped_region region{shdmem, read_write};
  int *i1 = static_cast<int*>(region.get_address());
  *i1 = 99;
  mapped_region region2{shdmem, read_only};
  int *i2 = static_cast<int*>(region2.get_address());
  std::cout << *i2 << '\n';
}

boost::interprocess::windows_shared_memory does not provide a member function truncate(). Instead, the size of the shared memory needs to be passed as the fourth parameter to the constructor.

Even though the class boost::interprocess::windows_shared_memory is not portable and can only be used on Windows, it is useful when data needs to be exchanged with an existing Windows program that uses this special kind of shared memory.

Shared memory is the fastest interprocess communication mechanism. The
operating system maps a memory segment in the address space of several
processes, so that several processes can read and write in that memory
segment without calling operating system functions. However, we need some
kind of synchronization between processes that read and write shared memory.

Consider what happens when a server process wants to send an HTML file
to a client process that resides in the same machine using network mechanisms:

  • The server must read the file to memory and pass it to the network
    functions, that copy that memory to the OS’s internal memory.
  • The client uses the network functions to copy the data from the OS’s
    internal memory to its own memory.

As we can see, there are two copies, one from memory to the network and
another one from the network to memory. And those copies are made using
operating system calls that normally are expensive. Shared memory avoids
this overhead, but we need to synchronize both processes:

  • The server maps a shared memory in its address space and also gets
    access to a synchronization mechanism. The server obtains exclusive
    access to the memory using the synchronization mechanism and copies
    the file to memory.
  • The client maps the shared memory in its address space. Waits until
    the server releases the exclusive access and uses the data.

Using shared memory, we can avoid two data copies, but we have to synchronize
the access to the shared memory segment.

To use shared memory, we have to perform 2 basic steps:

  • Request to the operating system a memory segment that can be shared
    between processes. The user can create/destroy/open this memory using
    a shared memory object: An
    object that represents memory that can be mapped concurrently into
    the address space of more than one process.
    .
  • Associate a part of that memory or the whole memory with the address
    space of the calling process. The operating system looks for a big
    enough memory address range in the calling process’ address space and
    marks that address range as an special range. Changes in that address
    range are automatically seen by other process that also have mapped
    the same shared memory object.

Once the two steps have been successfully completed, the process can start
writing to and reading from the address space to send to and receive data
from other processes. Now, let’s see how can we do this using Boost.Interprocess:

To manage shared memory, you just need to include the following header:

#include <boost/interprocess/shared_memory_object.hpp>

As we’ve mentioned we have to use the shared_memory_object
class to create, open and destroy shared memory segments that can be mapped
by several processes. We can specify the access mode of that shared memory
object (read only or read-write), just as if it was a file:

  • Create a shared memory segment. Throws if already created:
using namespace boost::interprocess;
shared_memory_object shm_obj
   (create_only                  
   ,"shared_memory"              
   ,read_write                   
   );
  • To open or create a shared memory segment:
using namespace boost::interprocess;
shared_memory_object shm_obj
   (open_or_create               
   ,"shared_memory"              
   ,read_only                    
   );
  • To only open a shared memory segment. Throws if does not exist:
using namespace boost::interprocess;
shared_memory_object shm_obj
   (open_only                    
   ,"shared_memory"              
   ,read_write                   
   );

When a shared memory object is created, its size is 0. To set the size
of the shared memory, the user must use the truncate
function call, in a shared memory that has been opened with read-write
attributes:

shm_obj.truncate(10000);

As shared memory has kernel or filesystem persistence, the user must explicitly
destroy it. The remove
operation might fail returning false if the shared memory does not exist,
the file is open or the file is still memory mapped by other processes:

using namespace boost::interprocess;
shared_memory_object::remove("shared_memory");

For more details regarding shared_memory_object
see the boost::interprocess::shared_memory_object
class reference.

Once created or opened, a process just has to map the shared memory object
in the process’ address space. The user can map the whole shared memory
or just part of it. The mapping process is done using the mapped_region class. The class represents
a memory region that has been mapped from a shared memory or from other
devices that have also mapping capabilities (for example, files). A mapped_region can be created from any
memory_mappable object
and as you might imagine, shared_memory_object
is a memory_mappable object:

using namespace boost::interprocess;
std::size_t ShmSize = ...


mapped_region region
   ( shm                      
   , read_write               
   , ShmSize/2                
   , ShmSize-ShmSize/2        
   );


region.get_address();


region.get_size();

The user can specify the offset from the mappable object where the mapped
region should start and the size of the mapped region. If no offset or
size is specified, the whole mappable object (in this case, shared memory)
is mapped. If the offset is specified, but not the size, the mapped region
covers from the offset until the end of the mappable object.

For more details regarding mapped_region
see the boost::interprocess::mapped_region
class reference.

Let’s see a simple example of shared memory use. A server process creates
a shared memory object, maps it and initializes all the bytes to a value.
After that, a client process opens the shared memory, maps it, and checks
that the data is correctly initialized:

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string>

int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   if(argc == 1){  
      
      struct shm_remove
      {
         shm_remove() { shared_memory_object::remove("MyName"); }
         ~shm_remove(){ shared_memory_object::remove("MyName"); }
      } remover;

      
      shared_memory_object shm (create_only, "MyName", read_write);

      
      shm.truncate(1000);

      
      mapped_region region(shm, read_write);

      
      std::memset(region.get_address(), 1, region.get_size());

      
      std::string s(argv[0]); s += " child ";
      if(0 != std::system(s.c_str()))
         return 1;
   }
   else{
      
      shared_memory_object shm (open_only, "MyName", read_only);

      
      mapped_region region(shm, read_only);

      
      char *mem = static_cast<char*>(region.get_address());
      for(std::size_t i = 0; i < region.get_size(); ++i)
         if(*mem++ != 1)
            return 1;   
   }
   return 0;
}

Boost.Interprocess provides portable shared
memory in terms of POSIX semantics. Some operating systems don’t support
shared memory as defined by POSIX:

  • Windows operating systems provide shared memory using memory backed
    by the paging file but the lifetime semantics are different from the
    ones defined by POSIX (see Native
    windows shared memory section for more information).
  • Some UNIX systems don’t fully support POSIX shared memory objects at
    all.

In those platforms, shared memory is emulated with mapped files created
in a «boost_interprocess» folder created in a temporary files
directory. In Windows platforms, if «Common AppData» key is present
in the registry, «boost_interprocess» folder is created in that
directory (in XP usually «C:\Documents and Settings\All Users\Application
Data» and in Vista «C:\ProgramData»). For Windows platforms
without that registry key and Unix systems, shared memory is created in
the system temporary files directory («/tmp» or similar).

Because of this emulation, shared memory has filesystem lifetime in some
of those systems.

shared_memory_object
provides a static remove
function to remove a shared memory objects.

This function can fail if the shared memory
objects does not exist or it’s opened by another process. Note that this
function is similar to the standard C int
remove(const char *path)
function. In UNIX systems, shared_memory_object::remove calls shm_unlink:

  • The function will remove the name of the shared memory object named
    by the string pointed to by name.
  • If one or more references to the shared memory object exist when is
    unlinked, the name will be removed before the function returns, but
    the removal of the memory object contents will be postponed until all
    open and map references to the shared memory object have been removed.
  • Even if the object continues to exist after the last function call,
    reuse of the name will subsequently cause the creation of a boost::interprocess::shared_memory_object
    instance to behave as if no shared memory object of this name exists
    (that is, trying to open an object with that name will fail and an
    object of the same name can be created again).

In Windows operating systems, current version supports an usually acceptable
emulation of the UNIX unlink behaviour: the file is renamed with a random
name and marked as to be deleted when the last open handle is
closed
.

Creating a shared memory segment and mapping it can be a bit tedious when
several processes are involved. When processes are related via fork()
operating system call in UNIX systems a simpler method is available using
anonymous shared memory.

This feature has been implemented in UNIX systems mapping the device \dev\zero
or just using the MAP_ANONYMOUS
in a POSIX conformant mmap
system call.

This feature is wrapped in Boost.Interprocess
using the anonymous_shared_memory() function, which returns a mapped_region object holding an anonymous
shared memory segment that can be shared by related processes.

Here is an example:

#include <boost/interprocess/anonymous_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <cstring>

int main ()
{
   using namespace boost::interprocess;
   try {
      
      mapped_region region(anonymous_shared_memory(1000));

      
      std::memset(region.get_address(), 1, region.get_size());

      
   }
   catch(interprocess_exception &ex){
      std::cout << ex.what() << std::endl;
      return 1;
   }
   return 0;
}

Once the segment is created, a fork() call can be used so that region is used to communicate two related
processes.

Windows operating system also offers shared memory, but the lifetime of
this shared memory is very different to kernel or filesystem lifetime.
The shared memory is created backed by the pagefile and it’s automatically
destroyed when the last process attached to the shared memory is destroyed.

Because of this reason, there is no effective way to simulate kernel or
filesystem persistence using native windows shared memory and Boost.Interprocess emulates shared memory using
memory mapped files. This assures portability between POSIX and Windows
operating systems.

However, accessing native windows shared memory is a common request of
Boost.Interprocess users because they
want to access to shared memory created with other process that don’t use
Boost.Interprocess. In order to manage
the native windows shared memory Boost.Interprocess
offers the windows_shared_memory
class.

Windows shared memory creation is a bit different from portable shared
memory creation: the size of the segment must be specified when creating
the object and can’t be specified through truncate
like with the shared memory object. Take in care that when the last process
attached to a shared memory is destroyed the shared
memory is destroyed
so there is no persistency
with native windows shared memory.

Sharing memory between services and user applications is also different.
To share memory between services and user applications the name of the
shared memory must start with the global namespace prefix "Global\\". This global namespace
enables processes on multiple client sessions to communicate with a service
application. The server component can create the shared memory in the global
namespace. Then a client session can use the «Global» prefix
to open that memory.

The creation of a shared memory object in the global namespace from a session
other than session zero is a privileged operation.

Let’s repeat the same example presented for the portable shared memory
object: A server process creates a shared memory object, maps it and initializes
all the bytes to a value. After that, a client process opens the shared
memory, maps it, and checks that the data is correctly initialized. Take
in care that if the server exits before the client
connects to the shared memory the client connection will fail
,
because the shared memory segment is destroyed when no proces is attached
to the memory.

This is the server process:

#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string>

int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   if(argc == 1){  
      
      windows_shared_memory shm (create_only, "MyName", read_write, 1000);

      
      mapped_region region(shm, read_write);

      
      std::memset(region.get_address(), 1, region.get_size());

      
      std::string s(argv[0]); s += " child ";
      if(0 != std::system(s.c_str()))
         return 1;
      
   }
   else{
      
      windows_shared_memory shm (open_only, "MyName", read_only);

      
      mapped_region region(shm, read_only);

      
      char *mem = static_cast<char*>(region.get_address());
      for(std::size_t i = 0; i < region.get_size(); ++i)
         if(*mem++ != 1)
            return 1;   
      return 0;
   }
   return 0;
}

As we can see, native windows shared memory needs synchronization to make
sure that the shared memory won’t be destroyed before the client is launched.

In many UNIX systems, the OS offers another shared memory memory mechanism,
XSI (X/Open System Interfaces) shared memory segments, also known as «System
V» shared memory. This shared memory mechanism is quite popular and
portable, and it’s not based in file-mapping semantics, but it uses special
functions (shmget, shmat, shmdt,
shmctl…).

Unlike POSIX shared memory segments, XSI shared memory segments are not
identified by names but by ‘keys’ usually created with ftok.
XSI shared memory segments have kernel lifetime and must be explicitly
removed. XSI shared memory does not support copy-on-write and partial shared
memory mapping but it supports anonymous shared memory.

Boost.Interprocess offers simple (xsi_shared_memory)
and managed (managed_xsi_shared_memory)
shared memory classes to ease the use of XSI shared memory. It also wraps
key creation with the simple xsi_key
class.

Let’s repeat the same example presented for the portable shared memory
object: A server process creates a shared memory object, maps it and initializes
all the bytes to a value. After that, a client process opens the shared
memory, maps it, and checks that the data is correctly initialized.

This is the server process:

#include <boost/interprocess/xsi_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string>

using namespace boost::interprocess;

void remove_old_shared_memory(const xsi_key &key)
{
   try {
      xsi_shared_memory xsi(open_only, key);
      xsi_shared_memory::remove(xsi.get_shmid());
   }
   catch(interprocess_exception &e){
      if(e.get_error_code() != not_found_error)
         throw;
   }
}

int main(int argc, char *argv[])
{
   if(argc == 1){  
      
      xsi_key key(argv[0], 1);

      remove_old_shared_memory(key);

      
      xsi_shared_memory shm (create_only, key, 1000);

      
      struct shm_remove
      {
         int shmid_;
         shm_remove(int shmid) : shmid_(shmid){}
         ~shm_remove(){ xsi_shared_memory::remove(shmid_); }
      } remover(shm.get_shmid());

      
      mapped_region region(shm, read_write);

      
      std::memset(region.get_address(), 1, region.get_size());

      
      std::string s(argv[0]); s += " child ";
      if(0 != std::system(s.c_str()))
         return 1;
   }
   else{
      
      xsi_key key(argv[0], 1);

      
      xsi_shared_memory shm (open_only, key);

      
      mapped_region region(shm, read_only);

      
      char *mem = static_cast<char*>(region.get_address());
      for(std::size_t i = 0; i < region.get_size(); ++i)
         if(*mem++ != 1)
            return 1;   
   }
   return 0;
}

File mapping is the association of a file’s contents with a portion of
the address space of a process. The system creates a file mapping to associate
the file and the address space of the process. A mapped region is the portion
of address space that the process uses to access the file’s contents. A
single file mapping can have several mapped regions, so that the user can
associate parts of the file with the address space of the process without
mapping the entire file in the address space, since the file can be bigger
than the whole address space of the process (a 9GB DVD image file in a
usual 32 bit systems). Processes read from and write to the file using
pointers, just like with dynamic memory. File mapping has the following
advantages:

  • Uniform resource use. Files and memory can be treated using the same
    functions.
  • Automatic file data synchronization and cache from the OS.
  • Reuse of C++ utilities (STL containers, algorithms) in files.
  • Shared memory between two or more applications.
  • Allows efficient work with a large files, without mapping the whole
    file into memory
  • If several processes use the same file mapping to create mapped regions
    of a file, each process’ views contain identical copies of the file
    on disk.

File mapping is not only used for interprocess communication, it can be
used also to simplify file usage, so the user does not need to use file-management
functions to write the file. The user just writes data to the process memory,
and the operating systems dumps the data to the file.

When two processes map the same file in memory, the memory that one process
writes is seen by another process, so memory mapped files can be used as
an interprocess communication mechanism. We can say that memory-mapped
files offer the same interprocess communication services as shared memory
with the addition of filesystem persistence. However, as the operating
system has to synchronize the file contents with the memory contents, memory-mapped
files are not as fast as shared memory.

To use memory-mapped files, we have to perform 2 basic steps:

  • Create a mappable object that represent an already created file of
    the filesystem. This object will be used to create multiple mapped
    regions of the the file.
  • Associate the whole file or parts of the file with the address space
    of the calling process. The operating system looks for a big enough
    memory address range in the calling process’ address space and marks
    that address range as an special range. Changes in that address range
    are automatically seen by other process that also have mapped the same
    file and those changes are also transferred to the disk automatically.

Once the two steps have been successfully completed, the process can start
writing to and reading from the address space to send to and receive data
from other processes and synchronize the file’s contents with the changes
made to the mapped region. Now, let’s see how can we do this using Boost.Interprocess:

To manage mapped files, you just need to include the following header:

#include <boost/interprocess/file_mapping.hpp>

First, we have to link a file’s contents with the process’ address space.
To do this, we have to create a mappable object that represents that file.
This is achieved in Boost.Interprocess
creating a file_mapping
object:

using namespace boost::interprocess;
file_mapping m_file
   ("/usr/home/file"       
   ,read_write             
   );

Now we can use the newly created object to create mapped regions. For more
details regarding this class see the boost::interprocess::file_mapping
class reference.

After creating a file mapping, a process just has to map the shared memory
in the process’ address space. The user can map the whole shared memory
or just part of it. The mapping process is done using the mapped_region class. as we have said
before The class represents a memory region that has been mapped from a
shared memory or from other devices that have also mapping capabilities:

using namespace boost::interprocess;
std::size_t FileSize = ...


mapped_region region
   ( m_file                   
   , read_write               
   , FileSize/2               
   , FileSize-FileSize/2      
   );


region.get_address();


region.get_size();

The user can specify the offset from the file where the mapped region should
start and the size of the mapped region. If no offset or size is specified,
the whole file is mapped. If the offset is specified, but not the size,
the mapped region covers from the offset until the end of the file.

If several processes map the same file, and a process modifies a memory
range from a mapped region that is also mapped by other process, the changes
are inmedially visible to other processes. However, the file contents on
disk are not updated immediately, since that would hurt performance (writing
to disk is several times slower than writing to memory). If the user wants
to make sure that file’s contents have been updated, it can flush a range
from the view to disk. When the function returns, the flushing process
has started but there is no guarantee that all data has been written to
disk:

region.flush();


region.flush(offset);


region.flush(offset, size);

Remember that the offset is not an offset
on the file, but an offset in the mapped region. If a region covers the
second half of a file and flushes the whole region, only the half of the
file is guaranteed to have been flushed.

For more details regarding mapped_region
see the boost::interprocess::mapped_region
class reference.

Let’s reproduce the same example described in the shared memory section,
using memory mapped files. A server process creates a shared memory segment,
maps it and initializes all the bytes to a value. After that, a client
process opens the shared memory, maps it, and checks that the data is correctly
initialized::

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <cstddef>
#include <cstdlib>

int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   
   const char *FileName  = "file.bin";
   const std::size_t FileSize = 10000;

   if(argc == 1){ 
      {  
         file_mapping::remove(FileName);
         std::filebuf fbuf;
         fbuf.open(FileName, std::ios_base::in | std::ios_base::out
                              | std::ios_base::trunc | std::ios_base::binary);
         
         fbuf.pubseekoff(FileSize-1, std::ios_base::beg);
         fbuf.sputc(0);
      }

      
      struct file_remove
      {
         file_remove(const char *FileName)
            : FileName_(FileName) {}
         ~file_remove(){ file_mapping::remove(FileName_); }
         const char *FileName_;
      } remover(FileName);

      
      file_mapping m_file(FileName, read_write);

      
      mapped_region region(m_file, read_write);

      
      void * addr       = region.get_address();
      std::size_t size  = region.get_size();

      
      std::memset(addr, 1, size);

      
      std::string s(argv[0]); s += " child ";
      if(0 != std::system(s.c_str()))
         return 1;
   }
   else{  
      {  
         file_mapping m_file(FileName, read_only);

         mapped_region region(m_file, read_only);

         
         void * addr       = region.get_address();
         std::size_t size  = region.get_size();

         
         const char *mem = static_cast<char*>(addr);
         for(std::size_t i = 0; i < size; ++i)
            if(*mem++ != 1)
               return 1;   
      }
      {  
         std::filebuf fbuf;
         fbuf.open(FileName, std::ios_base::in | std::ios_base::binary);

         
         std::vector<char> vect(FileSize, 0);
         fbuf.sgetn(&vect[0], std::streamsize(vect.size()));

         
         const char *mem = static_cast<char*>(&vect[0]);
         for(std::size_t i = 0; i < FileSize; ++i)
            if(*mem++ != 1)
               return 1;   
      }
   }

   return 0;
}

As we have seen, both shared_memory_object
and file_mapping objects
can be used to create mapped_region
objects. A mapped region created from a shared memory object or a file
mapping are the same class and this has many advantages.

One can, for example, mix in STL containers mapped regions from shared
memory and memory mapped files. Libraries that only depend on mapped regions
can be used to work with shared memory or memory mapped files without recompiling
them.

In the example we have seen, the file or shared memory contents are mapped
to the address space of the process, but the address was chosen by the
operating system.

If several processes map the same file/shared memory, the mapping address
will be surely different in each process. Since each process might have
used its address space in a different way (allocation of more or less dynamic
memory, for example), there is no guarantee that the file/shared memory
is going to be mapped in the same address.

If two processes map the same object in different addresses, this invalidates
the use of pointers in that memory, since the pointer (which is an absolute
address) would only make sense for the process that wrote it. The solution
for this is to use offsets (distance) between objects instead of pointers:
If two objects are placed in the same shared memory segment by one process,
the address of each object will be different
in another process but the distance between them
(in bytes) will be the same
.

So the first advice when mapping shared memory and memory mapped files
is to avoid using raw pointers, unless you know what you are doing. Use
offsets between data or relative pointers to obtain pointer functionality
when an object placed in a mapped region wants to point to an object placed
in the same mapped region. Boost.Interprocess
offers a smart pointer called boost::interprocess::offset_ptr
that can be safely placed in shared memory and that can be used to point
to another object placed in the same shared memory / memory mapped file.

The use of relative pointers is less efficient than using raw pointers,
so if a user can succeed mapping the same file or shared memory object
in the same address in two processes, using raw pointers can be a good
idea.

To map an object in a fixed address, the user can specify that address
in the mapped region‘s
constructor:

mapped_region region ( shm                         
                     , read_write                  
                     , 0                           
                     , 0                           
                     , (void*)0x3F000000           
                     );

However, the user can’t map the region in any address, even if the address
is not being used. The offset parameter that marks the start of the mapping
region is also limited. These limitations are explained in the next section.

As mentioned, the user can’t map the memory mappable object at any address
and it can specify the offset of the mappable object that is equivalent
to the start of the mapping region to an arbitrary value. Most operating
systems limit the mapping address and the offset of the mappable object
to a multiple of a value called page size.
This is due to the fact that the operating system
performs mapping operations over whole pages
.

If fixed mapping address is used, offset and address
parameters should be multiples of that value. This value is, typically,
4KB or 8KB for 32 bit operating systems.

mapped_region region1( shm                   
                     , read_write            
                     , 1                     
                     , 1                     
                     , (void*)0x3F000000     
                     );


mapped_region region2( shm                   
                     , read_write            
                     , 0                     
                     , 1                     
                     , (void*)0x3F000001     
                     );

Since the operating system performs mapping operations over whole pages,
specifying a mapping size or offset
that are not multiple of the page size will waste more resources than necessary.
If the user specifies the following 1 byte mapping:

mapped_region region ( shm                    
                     , read_write             
                     , 0                      
                     , 1                      
                     );

The operating system will reserve a whole page that will not be reused
by any other mapping so we are going to waste (page
size — 1)
bytes. If we want to use efficiently operating system
resources, we should create regions whose size is a multiple of page size bytes. If the user specifies the following
two mapped regions for a file with which has 2*page_size
bytes:

mapped_region region1( shm                
                     , read_write         
                     , 0                  
                     , page_size/2        
                     );



mapped_region region2( shm                
                     , read_write         
                     , page_size/2        
                     , 3*page_size/2      
                     );

In this example, a half of the page is wasted in the first mapping and
another half is wasted in the second because the offset is not a multiple
of the page size. The mapping with the minimum resource usage would be
to map whole pages:

mapped_region region1( shm                
                     , read_write         
                     , 0                  
                     , page_size          
                     );


mapped_region region2( shm                
                     , read_write         
                     , page_size          
                     , page_size          
                     );

How can we obtain the page size? The
mapped_region class has
a static function that returns that value:

std::size_t page_size = mapped_region::get_page_size();

The operating system might also limit the number of mapped memory regions
per process or per system.

When two processes create a mapped region of the same mappable object, two
processes can communicate writing and reading that memory. A process could
construct a C++ object in that memory so that the second process can use
it. However, a mapped region shared by multiple processes, can’t hold any
C++ object, because not every class is ready to be a process-shared object,
specially, if the mapped region is mapped in different address in each process.

When placing objects in a mapped region and mapping that region in different
address in every process, raw pointers are a problem since they are only
valid for the process that placed them there. To solve this, Boost.Interprocess offers a special smart pointer
that can be used instead of a raw pointer. So user classes containing raw
pointers (or Boost smart pointers, that internally own a raw pointer) can’t
be safely placed in a process shared mapped region. These pointers must
be replaced with offset pointers, and these pointers must point only to
objects placed in the same mapped region if you want to use these shared
objects from different processes.

Of course, a pointer placed in a mapped region shared between processes
should only point to an object of that mapped region. Otherwise, the pointer
would point to an address that it’s only valid one process and other processes
may crash when accessing to that address.

References suffer from the same problem as pointers (mainly because they
are implemented as pointers). However, it is not possible to create a fully
workable smart reference currently in C++ (for example, operator
.()
can’t be overloaded). Because
of this, if the user wants to put an object in shared memory, the object
can’t have any (smart or not) reference as a member.

References will only work if the mapped region is mapped in the same base
address in all processes sharing a memory segment. Like pointers, a reference
placed in a mapped region should only point to an object of that mapped
region.

The virtual table pointer and the virtual table are in the address space
of the process that constructs the object, so if we place a class with
a virtual function or virtual base class, the virtual pointer placed in
shared memory will be invalid for other processes and they will crash.

This problem is very difficult to solve, since each process needs a different
virtual table pointer and the object that contains that pointer is shared
across many processes. Even if we map the mapped region in the same address
in every process, the virtual table can be in a different address in every
process. To enable virtual functions for objects shared between processes,
deep compiler changes are needed and virtual functions would suffer a performance
hit. That’s why Boost.Interprocess does
not have any plan to support virtual function and virtual inheritance in
mapped regions shared between processes.

Static members of classes are global objects shared by all instances of
the class. Because of this, static members are implemented as global variables
in processes.

When constructing a class with static members, each process has its own
copy of the static member, so updating a static member in one process does
not change the value of the static member the another process. So be careful
with these classes. Static members are not dangerous if they are just constant
variables initialized when the process starts, but they don’t change at
all (for example, when used like enums) and their value is the same for
all processes.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Формат файловой системы windows
  • The c compiler identification is unknown windows
  • Windows error reporting log
  • Как создать группу безопасности в windows 10
  • Kmixer sys windows xp