应该'managed_shared_memory'分配多少内存?(促进)

Cou*_*sen 11 c++ boost shared-memory interprocess multiprocess

我在寻找一个明确的答案(如果确实存在)有多少内存应该通过创建共享内存的静态块时被分配boost::interprocessmanaged_shared_memory.即使是官方的例子似乎也会分配任意大块的内存.

考虑以下结构:

// Example: simple struct with two 4-byte fields
struct Point2D {
  int x, y;
};
Run Code Online (Sandbox Code Playgroud)

我最初的反应是必要的大小是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));
Run Code Online (Sandbox Code Playgroud)

什么读/写操作导致seg-faults?堆栈操作?临时分配segment.construct()?分配共享内存时需要多少开销?

通过试错我发现,通过4大小乘可以为上述结构的工作,但是当我开始增加更多的领域,以我的分崩离析struct.所以,这是一个糟糕的黑客.

有些人可能会争辩说,"内存很便宜",在现代电脑,但我不同意这种理念和分配不喜欢比我更需要的,如果我能避免它.我昨天在Boost文档中挖了一遍,找不到任何建议.这是今天要学习新东西的!

ice*_*ime 8

从文档的这一段:

存储器算法是放置在共享存储器/存储器映射文件段的第一个字节中的对象.

内存段的布局:

 ____________ __________ ____________________________________________  
|            |          |                                            | 
|   memory   | reserved |  The memory algorithm will return portions | 
| algorithm  |          |  of the rest of the segment.               | 
|____________|__________|____________________________________________| 
Run Code Online (Sandbox Code Playgroud)

该库在段的开头有一个额外的内存开销,因此占用了所请求大小的几个字节.根据这篇文章这篇文章,无法确定这个确切的附加字节数:

您无法计算它,因为根据您的分配/取消分配模式,存在运行时更改的内存分配bookeeping和碎片问题.并且共享内存由操作系统分配页面(Windows上的Linux 64k上的4K),因此任何分配都将实际分配到页面:

    managed_shared_memory segment(create_only, "name", 20);
Run Code Online (Sandbox Code Playgroud)

会浪费同样的记忆:

    managed_shared_memory segment(create_only, "name", 4096);
Run Code Online (Sandbox Code Playgroud)