【发布时间】:2014-02-27 08:58:51
【问题描述】:
我有这个结构:
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 以使其也可以从其他应用程序访问。我看到this 和that 的例子,但我根本不明白allocator 的东西(为什么我需要一个字符分配器?我需要在这里使用什么样的分配器等等......)
谁能解释我如何把这个容器放到共享内存中?
真的谢谢...
编辑:
好的,我添加了我的代码:
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.
有什么想法吗???
【问题讨论】:
-
您需要一个字符分配器来分配
char对象的连续区域。你知道,当你分配字符串时你会做什么? (从样本中可以很清楚地看到)。请向我们展示实际代码以及您遇到的问题。目前看来您希望我们为您工作? -
问题是我不明白我是否有像示例中那样的分配器,但由于我没有字符串,我想我也不需要那个分配器。所以我想我必须像这个例子一样构建它。 boost.org/doc/libs/1_47_0/doc/html/interprocess/…。如何从其他应用程序访问容器?对不起,我不希望你做这项工作,只是我不知道该怎么做?这是我第一次使用共享内存。
标签: c++ visual-studio-2008 boost shared-memory multi-index