“托管共享内存”应该设置多少内存分配? (促进)
我正在寻找一个明确的答案(如果确实存在的话),关于通过 boost::interprocess
的 managed_shared_memory
。即使官方示例似乎分配任意大的内存块。
考虑以下结构:
// Example: simple struct with two 4-byte fields
struct Point2D {
int x, y;
};
我最初的反应是必要的大小为 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 文档,但找不到任何建议。今天就来学习一些新东西吧!
I'm looking for a definitive answer (if indeed one exists) on how much memory should be allocated when creating a static chunks of shared memory via boost::interprocess
's managed_shared_memory
. Even official examples seem to allocate arbitrarily large chunks of memory.
Consider the following structure:
// Example: simple struct with two 4-byte fields
struct Point2D {
int x, y;
};
My initial reaction is that the necessary size would be 8 bytes, or sizeof(Point2D)
. This fails miserably when I attempt to construct an object, giving me seg-faults at runtime.
// BAD: 8 bytes is nowhere near enough memory allocated.
managed_shared_memory segment(create_only, "My shared memory", sizeof(Point2D));
What read/write operation is causing seg-faults? Stack operations? Temporarily allocations within segment.construct()
? How much overhead is necessary when allocating shared memory?
By trial-and-error I found that multiplying the size by 4 can work for the above structure, but falls apart when I start adding more fields to my struct
. So, that reeks of a bad hack.
Some might argue that "memory is cheap" in the modern PC, but I disagree with this philosophy and dislike allocating more than I need to, if I can avoid it. I dug around the Boost docs yesterday and couldn't find any recommendations. Here's to learning something new today!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自本段:
内存段的布局:
库在段的开头有额外的内存开销,因此占用了您请求的大小的几个字节。根据这篇文章和这篇文章,无法确定额外字节的确切数量:
From this paragraph of the documentation :
Layout of the memory segment :
The library has an extra memory overhead sitting at the beginning of the segment, thus occupying a few bytes of your requested size. According to this post and this post, this exact number of additional bytes cannot be determined :
像使用操作系统的内存页面大小之类的东西是可行的。在我的例子中,这是有效的。
使用 boost::managed_shared_memory 允许您在生成的空间中构造对象。类似....
Something like using the OS'es memory page size works. In my case this works..
Using boost::managed_shared_memory allows you to construct objects in the resulting space. Something like....