sho*_*bhu 14 c++ stl shared-memory
我有以下代码模式:
class A {
double a, b, c;
...
};
class B {
map<int, A> table; // Can have maximum of MAX_ROWS elements.
...
};
class C {
B entries;
queue<int> d;
queue<int> e;
...
};
Run Code Online (Sandbox Code Playgroud)
现在我想将一个C类型的对象存储在共享内存中,以便不同的进程可以追加,更新和读取它.我怎样才能做到这一点?(注意:我知道如何在共享内存中存储一个具有固定大小的简单C数组.另外,请记住B.table可能有任意条目.
Nim*_*Nim 17
使用boost :: interprocess,此库公开此功能.
编辑:以下是您需要做的一些更改:
该示例已经定义了一个将从共享内存块分配的分配器,您需要将其传递给map和queue.这意味着您必须更改定义:
class B
{
map<int, A, less<int>, MapShmemAllocator> table;
// Constructor of the map needs the instance of the allocator
B(MapShmemAllocator& alloc) : table(less<int>(), alloc)
{ }
}
Run Code Online (Sandbox Code Playgroud)
因为queue,这有点复杂,因为它实际上只是一个适配器,因此您需要将实际的实现类作为模板参数传递:
typedef queue<int, deque<int, QueueShmemAllocator> > QueueType;
Run Code Online (Sandbox Code Playgroud)
现在你的班级C略有变化:
class C
{
B entries;
QueueType d, e;
C(MapShmemAllocator& allocM, QueueShmemAllocator& allocQ) : entries(allocM), d(allocQ), e(allocQ)
{ }
}
Run Code Online (Sandbox Code Playgroud)
现在,从段管理器,C使用allocator 构造一个实例.
C *pC = segment.construct<C>("CInst")(allocM_inst, allocQ_inst);
Run Code Online (Sandbox Code Playgroud)
我认为应该这样做.注意:您需要提供两个分配器(一个用于queue,一个用于map),不确定是否可以从同一个段管理器构造两个分配器,但我不明白为什么不这样做.