共有メモリでのマップの使用法を学ぶために私が書いた最近の例を次に示します。おそらくコンパイルされるので、要件に合わせて試すことができます。
共有メモリを作成し、それにマップを配置するサーバー プロセスのコード:-
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>
int main ()
{
using namespace boost::interprocess;
// remove earlier existing SHM
shared_memory_object::remove("SharedMemoryName");
// create new
managed_shared_memory segment(create_only,"SharedMemoryName",65536);
//Note that map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>,
//so the allocator must allocate that pair.
typedef int KeyType;
typedef float MappedType;
typedef std::pair<const int, float> ValueType;
//allocator of for the map.
typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator;
//third parameter argument is the ordering function is used to compare the keys.
typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MySHMMap;
//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc_inst (segment.get_segment_manager());
// offset ptr within SHM for map
offset_ptr<MySHMMap> m_pmap = segment.construct<MySHMMap>("MySHMMapName")(std::less<int>(), alloc_inst);
//Insert data in the map
for(int i = 0; i < 10; ++i)
{
m_pmap->insert(std::pair<const int, float>(i, (float)i));
}
return 0;
}
メモリにアタッチしてマップのデータにアクセスするクライアント プロセスのコード。
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>
#include <iostream>
int main ()
{
using namespace boost::interprocess;
try
{
managed_shared_memory segment(open_or_create, "SharedMemoryName",65536);
//Again the map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>, so the allocator must allocate that pair.
typedef int KeyType;
typedef float MappedType;
typedef std::pair<const int, float> ValueType;
//Assign allocator
typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator;
//The map
typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MySHMMap;
//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc_inst (segment.get_segment_manager());
//access the map in SHM through the offset ptr
MySHMMap :: iterator iter;
offset_ptr<MySHMMap> m_pmap = segment.find<MySHMMap>("MySHMMapName").first;
iter=m_pmap->begin();
for(; iter!=m_pmap->end();iter++)
{
std::cout<<"\n "<<iter->first<<" "<<iter->second;
}
}catch(std::exception &e)
{
std::cout<<" error " << e.what() <<std::endl;
shared_memory_object::remove("SharedMemoryName");
}
return 0;
}
クライアント プロセスのコードでは、「名前」とオフセット ポインターを使用して、他のプロセスがサーバー プロセスによって SHM で作成されたマップ コンテンツにアタッチしてアクセスする方法について説明します。しかし、新しい共有メモリ セグメントの作成中にサイズ (ここでは '65536') を割り当てると、サイズを縮小できるかどうかはわかりませんが、おそらく SHM を拡張するために共有メモリのチャンクをさらに作成できます...
それが役に立ったことを願っています...