C++ 地图<;int,void*>;在共享内存中使用Boost::interprocess

C++ 地图<;int,void*>;在共享内存中使用Boost::interprocess,c++,boost,ipc,shared-memory,C++,Boost,Ipc,Shared Memory,我正在尝试在共享内存中构造以下类型的映射 我创建的共享内存区域如下所示: managed_shared_memory segment(create_only ,"MyMap" ,size); ShMemAllocator_t alloc_inst (segment.get_segment_manager()); map = segment.construct<MyMap_t>("MyMap")

我正在尝试在共享内存中构造以下类型的映射

我创建的共享内存区域如下所示:

 managed_shared_memory segment(create_only ,"MyMap"  ,size);       

ShMemAllocator_t alloc_inst (segment.get_segment_manager());

 map =   segment.construct<MyMap_t>("MyMap")      
                             (std::less<int>() 
                             ,alloc_inst); 
托管共享内存段(仅创建“MyMap”,大小);
ShMemAllocator_t alloc_inst(segment.get_segment_manager());
map=段.构造(“MyMap”)
(std::less()
,alloc_inst);
图中的值如下所示:

       typedef pair<MutexType, boost::interprocess::offset_ptr<void> > ValueType ; 
typedef struct  mutex_struct{ 
   sharable_lock<interprocess_mutex> read_lock(interprocess_mutex, defer_lock); 
  scoped_lock<interprocess_mutex> write_lock(interprocess_mutex, defer_lock); 
} MutexType;
typedef对ValueType;
MutexType本身就是一个包含读写互斥(使用读锁和写锁)的结构; 定义如下:

       typedef pair<MutexType, boost::interprocess::offset_ptr<void> > ValueType ; 
typedef struct  mutex_struct{ 
   sharable_lock<interprocess_mutex> read_lock(interprocess_mutex, defer_lock); 
  scoped_lock<interprocess_mutex> write_lock(interprocess_mutex, defer_lock); 
} MutexType;
typedef struct mutex_struct{
可共享锁定读取锁定(进程间互斥、延迟锁定);
作用域锁定写入锁定(进程间互斥、延迟锁定);
}互斥类型;
“size”是贴图的总大小(就对象而言,即所有void指针指向的数据大小之和)


如何确保此void*数据也位于我创建的内存段中,如何在现有共享内存区域中实例化它)。这样做的原因是我只想分配一次这个大缓冲区,但要重复地删除/添加对象(映射模拟缓存),我还没有找到一种方法,可以在映射的同一内存段中分配多个对象。此外,试图分配MutexType对会返回一个编译错误,说明没有提供“call”运算符

您可以在分配器中使用重新绑定


默认的std::分配器是无状态的。共享内存分配器将具有状态,因此您需要弄清楚如何在不同类型的分配器之间复制状态。

您基本上已经做到了。调用您在共享内存中分配的任何对象类型
SecondValue\t
。代替
ShMemAllocator\u t
,定义不同的进程间分配器类型,例如
SecondValueAllocator\u t
,用于分配
SecondValueAllocator\u t
对象。每当您想在映射中插入
ValueType
对象时,
ValueType
对象的第二个值将与
SecondValueAllocator\t
实例一起分配

下面是一个完整的示例,部分使用中的代码:

#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#定义共享内存名称“SO13783012 MyMap”
// https://stackoverflow.com/questions/13783012/map-of-int-void-in-shared-memory-using-boostinterprocess
使用名称空间boost::interprocess;
typedef int SecondValue\u t;
typedef分配器SecondValueAllocator\u t;
typedef结构互斥体{
//...
}互斥类型;
typedef std::pair ValueType;
typedef映射::value_type MyMapValueType;
typedef分配器MyMapEntryAllocator\u t;
typedef-map-MyMap\t;
结构共享数据{
私人:
typedef boost::进程间::进程间可升级的互斥体可升级的互斥体类型;
可变可升级的_互斥体_型互斥体;
我的地图是我的地图;
公众:
共享数据(常量MyMapEntryAllocator&alloc)
:MyMap(MyMap\u t::key\u compare(),alloc)
{
}
//尝试获取给定键“k”的映射值。如果成功,则映射值为
//复制到'out'中并返回'true'。否则,返回'false'且不修改
//“出去”。
bool try_get(MyMap_t::mapped_type&out,MyMap_t::key_type k)常量{
boost::进程间::共享锁(互斥锁);
MyMap\u t::const\u迭代器pos=my\u map.find(k);
if(pos!=my_map.end()){
输出=位置->秒;
返回true;
}
返回false;
}
void put(MyMap\u t::key\u type k,MyMap\u t::mapped\u type v){
boost::进程间::作用域锁定(互斥);
my_map.insert(MyMap_t::value_type(my_map.size(),v));
}
};
int main(int argc,char*argv[])
{
如果(argc!=2){

标准::cerr(我知道这有点旧,但是)我注意到,在您的示例中,writer锁实际上不起作用。如果生成多个writer child,则I的值可能未定义,并且您将尝试使用相同的值插入一对,这是由于并发性问题(如果该示例仅显示在最后一个键之后添加另一个项),而put方法应收集当前大小of映射并插入大小为+1.Hi@Steve的元素,我不确定我是否遵循了。为什么
I
的值未定义?在for循环中,您计算++I,直到没有从d返回值。try_get-让我们假设我现在是10。稍后,您尝试将键I=10与d.put(I,v=std::make_pair(MutexType(),p))放在一起;如果同时另一个子写入进程已经在映射中放入了某些内容-10将是重复的。只需假设两个子写入程序-每次执行一行-都到达i=10,但是child1首先放入一个新条目,i=10-因此第二个子写入程序将失败。这是因为i=10不在任何写入/读取范围之内lock@Steve:啊!是的,你是好的,谢谢你指出这一点。
char_alloc char_alloc_obj;
char * ptr = new (char_alloc_obj.allocate(size)) char[size];
void * vptr = (void *) ptr;
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <utility>

#include <boost/scope_exit.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/allocators/private_node_allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/sync/interprocess_upgradable_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/interprocess/sync/upgradable_lock.hpp>

#define SHARED_MEMORY_NAME "SO13783012-MyMap"

// https://stackoverflow.com/questions/13783012/map-of-int-void-in-shared-memory-using-boostinterprocess

using namespace boost::interprocess;

typedef int SecondValue_t;
typedef allocator<SecondValue_t, managed_shared_memory::segment_manager> SecondValueAllocator_t;

typedef struct mutex_struct {
    //...
} MutexType;

typedef std::pair<MutexType, SecondValueAllocator_t::pointer> ValueType;

typedef map<int, ValueType>::value_type MyMapValueType;
typedef allocator<MyMapValueType, managed_shared_memory::segment_manager> MyMapEntryAllocator_t;
typedef map<int, ValueType, std::less<int>, MyMapEntryAllocator_t> MyMap_t;

struct shared_data {
private:
    typedef boost::interprocess::interprocess_upgradable_mutex upgradable_mutex_type;

    mutable upgradable_mutex_type mutex;
    MyMap_t my_map;

public:
    shared_data(const MyMapEntryAllocator_t& alloc)
        : my_map(MyMap_t::key_compare(), alloc)
    {
    }

    // Tries to get the mapped value for the given key `k'. If successful, the mapped value is
    // copied into `out' and `true' is returned. Otherwise, returns `false' and does not modify
    // `out'.
    bool try_get(MyMap_t::mapped_type& out, MyMap_t::key_type k) const {
        boost::interprocess::sharable_lock<upgradable_mutex_type> lock(mutex);
        MyMap_t::const_iterator pos = my_map.find(k);
        if (pos != my_map.end()) {
            out = pos->second;
            return true;
        }
        return false;
    }

    void put(MyMap_t::key_type k, MyMap_t::mapped_type v) {
        boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mutex);
        my_map.insert(MyMap_t::value_type(my_map.size(), v));
    }
};

int main(int argc, char *argv[])
{
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " WHICH\n";
        return EXIT_FAILURE;
    }

    const std::string which = argv[1];

    if (which == "parent") {
        shared_memory_object::remove(SHARED_MEMORY_NAME);
        BOOST_SCOPE_EXIT(argc) {
            shared_memory_object::remove(SHARED_MEMORY_NAME);
        } BOOST_SCOPE_EXIT_END;
        managed_shared_memory shm(create_only, SHARED_MEMORY_NAME, 65536);

        MyMapEntryAllocator_t entry_alloc(shm.get_segment_manager());
        shared_data& d = *shm.construct<shared_data>("theSharedData")(entry_alloc);

        SecondValueAllocator_t second_value_alloc(shm.get_segment_manager());

        // Insert some test data.
        SecondValueAllocator_t::pointer p;
        p = second_value_alloc.allocate(1);
        second_value_alloc.construct(p, -3);
        d.put(0, std::make_pair(MutexType(), p));
        p = second_value_alloc.allocate(1);
        second_value_alloc.construct(p, 70);
        d.put(1, std::make_pair(MutexType(), p));
        p = second_value_alloc.allocate(1);
        second_value_alloc.construct(p, -18);
        d.put(2, std::make_pair(MutexType(), p));
        p = second_value_alloc.allocate(1);
        second_value_alloc.construct(p, 44);
        d.put(3, std::make_pair(MutexType(), p));
        p = second_value_alloc.allocate(1);
        second_value_alloc.construct(p, 0);
        d.put(4, std::make_pair(MutexType(), p));

        // Go to sleep for a minute - gives us a chance to start a child process.
        sleep(60);
    } else {
        managed_shared_memory shm(open_only, SHARED_MEMORY_NAME);
        std::pair<shared_data *, std::size_t> find_res = shm.find<shared_data>("theSharedData");
        if (!find_res.first) {
            std::cerr << "Failed to find `theSharedData'.\n";
            return EXIT_FAILURE;
        }
        shared_data& d = *find_res.first;

        MyMap_t::mapped_type v;
        int i = 0;
        for (; d.try_get(v, i); ++i) {
            std::cout << i << ": " << *v.second << '\n';
        }

        // Add an entry.
        srand(time(NULL));
        SecondValueAllocator_t second_value_alloc(shm.get_segment_manager());
        SecondValueAllocator_t::pointer p = second_value_alloc.allocate(1);
        second_value_alloc.construct(p, (rand() % 200) - 100);
        d.put(i, v = std::make_pair(MutexType(), p));
        std::cout << "placed " << *v.second << " into the map.\n";
    }

    return EXIT_SUCCESS;
}
./SO13783012 parent ./SO13783012 child > ./SO13783012 child 0: -3 1: 70 2: -18 3: 44 4: 0 placed 5: -63 into the map. > ./SO13783012 child 0: -3 1: 70 2: -18 3: 44 4: 0 5: -63 placed 6: -42 into the map. > ./SO13783012 child 0: -3 1: 70 2: -18 3: 44 4: 0 5: -63 6: -42 placed 7: -28 into the map.