我正在寻找关于在通过 boost::interprocess
的 managed_shared_memory 创建静态共享内存块时应该分配多少内存的明确答案(如果确实存在的话)
。连official examples似乎分配arbitrarily large内存块。
考虑以下结构:
// Example: simple struct with two 4-byte fields
struct Point2D {
int x, y;
};
我最初的 react 是必要的大小是 8 个字节,或 sizeof(Point2D)
。当我尝试构造一个对象时,这惨遭失败,在运行时出现段错误。
// BAD: 8 bytes is nowhere near enough memory allocated.
managed_shared_memory segment(create_only, "My shared memory", sizeof(Point2D));
什么读/写操作导致段错误?堆栈操作?在 segment.construct()
中临时分配?分配共享内存时需要多少开销?
通过反复试验,我发现将大小乘以 4 可以用于上述结构,但是当我开始向我的 struct
添加更多字段时,它就会崩溃。所以,这有点像糟糕的黑客攻击。
有些人可能会争辩说现代 PC 中的“内存很便宜”,但我不同意这种理念,并且不喜欢分配比我需要的更多的内存,如果我能避免的话。我昨天浏览了 Boost 文档,但找不到任何建议。今天是为了学习新东西!
最佳答案
来自 this paragraph文档:
The memory algorithm is an object that is placed in the first bytes of a shared memory/memory mapped file segment.
内存段布局:
____________ __________ ____________________________________________
| | | |
| memory | reserved | The memory algorithm will return portions |
| algorithm | | of the rest of the segment. |
|____________|__________|____________________________________________|
该库在段的开头有额外的内存开销,因此占用了您请求大小的几个字节。根据this post和 this post ,这个额外字节的确切数量无法确定:
You can't calculate it, because there are memory allocation bookeeping and fragmentation issues that change in runtime depending on your allocation/deallocation pattern. And shared memory is allocated by pages by the OS (4K on linux 64k on windows), so any allocation will be in practice allocated rounded to a page:
managed_shared_memory segment(create_only, "name", 20);
will waste the same memory as:
managed_shared_memory segment(create_only, "name", 4096);
关于c++ - 'managed_shared_memory' 应该分配多少内存? ( boost ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166642/