我正在寻找一个明确的答案(如果确实存在),在创建静态的共享内存块时应分配多少内存 boost::interprocess
的 managed_shared_memory
。甚至 官方的例子 似乎分配 任意大 大块的记忆。
考虑以下结构:
// Example: simple struct with two 4-byte fields
struct Point2D {
int x, y;
};
我最初的反应是必要的大小是8个字节,或者 sizeof(Point2D)
。当我尝试构造一个对象时,这会失败,在运行时给出了seg-fault。
// BAD: 8 bytes is nowhere near enough memory allocated.
managed_shared_memory segment(create_only, "My shared memory", sizeof(Point2D));
什么读/写操作导致seg-faults?堆栈操作?临时分配 segment.construct()
?分配共享内存时需要多少开销?
通过反复试验,我发现将大小乘以4可以适用于上述结构,但是当我开始向我添加更多字段时会崩溃 struct
。所以,这是一个糟糕的黑客。
有些人可能认为现代个人电脑中的“记忆力很便宜”,但我不同意这种理念,不喜欢分配比我需要的更多,如果我可以避免它。我昨天在Boost文档中挖了一遍,找不到任何建议。这是今天要学习新东西的!
从 这一段 文件:
内存算法是一个对象
放在a的第一个字节中
共享内存/内存映射文件
分割。
内存段的布局:
____________ __________ ____________________________________________
| | | |
| memory | reserved | The memory algorithm will return portions |
| algorithm | | of the rest of the segment. |
|____________|__________|____________________________________________|
该库在段的开头有一个额外的内存开销,因此占用了所请求大小的几个字节。根据 这个帖子 和 这个帖子,这个确切的附加字节数无法确定:
你无法计算它,因为那里
是内存分配bookeeping和
变化的碎片问题
运行时取决于你的
分配/解除分配模式。和
共享内存由页面分配
通过操作系统(Linux on 64k上的4K)
windows),所以任何分配都会
在实践中分配四舍五入到
页:
managed_shared_memory segment(create_only, "name", 20);
会浪费同样的记忆:
managed_shared_memory segment(create_only, "name", 4096);
使用OS'es内存页面大小的工作原理。在我的情况下,这工作..
off_t size = sizeof(class1) + (sizeof(class2) * 3);
// round up to the OS page size.
long page_size = sysconf(_SC_PAGE_SIZE);
size = ((size / page_size) + (size % page_size ? 1 : 0)) * page_size;
使用boost :: managed_shared_memory可以在结果空间中构造对象。就像是....
shared_memory_object::remove(m_name.c_str());
m_shared.reset(new managed_shared_memory(create_only, "myspace", size));
m_class1 = m_shared->construct<class1>("class1")();
m_class2 = m_shared->construct<class2>("class2")[3]();