共享内存中的multi_index容器

时间:2014-02-27 08:58:51

标签: c++ visual-studio-2008 boost shared-memory multi-index

我有这个结构:

struct myData
{   
    unsigned long id;
    int age; 
    int phone;

    myData(){};
    myData(unsigned long id_, int age_, int phone_)
        :id(id_),age(age_),phone(phone_){}
    ~myData(){};
};

这个multi_index容器:

typedef multi_index_container<
    myData, 
        indexed_by<    
            random_access<>,  // keep insertion order
            ordered_non_unique< member<myData, int, &myData::age> >
        >
> myDataContainerType;

typedef myDataContainerType::nth_index<1>::type myDataContainerType_by_Id;
myDataContainerType myDataContainer;

和这个插入函数:

bool insert(unsigned long id, int age, int phone) { 

    myDataContainerType::iterator it; 
    bool success; 
    boost::mutex::scoped_lock scoped_lock(mutex); // LOCK
    std::pair<myDataContainerType::iterator, bool> result = myDataContainer.push_back(myData(id, age, phone)); 
    it = result.first; 
    success = result.second; 
    if (success) 
        return true; 
    else 
        return false; 
} 

所以我想将这个muti_index容器放到shared memory以使其可以从其他应用程序访问。我看到thisthat示例,但我完全不理解allocator的东西(为什么我需要一个char分配器?这里需要使用哪种分配器等等......)

有人可以解释一下如何将这个容器放到共享内存中吗?

非常感谢...

修改

好的,我添加了我的代码:

myDataContainerType *myDataContainer ;

void createInSharedMemory()
{
    managed_shared_memory segment(create_only,"mySharedMemory", 65536);

    myDataContainer = segment.construct<myDataContainerType>
        ("MyContainer")            //Container's name in shared memory
        ( myDataContainerType::ctor_args_list()
        , segment.get_allocator<myData>());  //Ctor parameters

}

并尝试插入如下数据:

bool insert(unsigned long id, int age, int phone) { 

    myDataContainerType::iterator it; 
    bool success; 
    boost::mutex::scoped_lock scoped_lock(mutex); // LOCK
    std::pair<myDataContainerType::iterator, bool> result = myDataContainer->insert(MyData(id, age, phone));    

    it = result.first; 
    success = result.second; 
    if (success) 
        return true; 
    else 
        return false; 
} 

但是我在插入行中遇到了这个错误:(在offset_ptr.hpp中)

Unhandled exception at 0x000000013fa84748 in LDB_v1.exe: 0xC0000005: Access violation reading location 0x0000000001d200d0.

任何想法,请

1 个答案:

答案 0 :(得分:0)

调用myDataContainer后,您是否检查过segment.construct是否为非空?也许您需要使用segment.find_or_construct代替。