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

时间:2010-11-12 16:14:53

标签: c++ boost shared-memory interprocess multiprocess

我正在寻找一个确定的答案(如果确实存在的话),在通过boost::interprocess的{​​{1}}创建静态的共享内存块时应该分配多少内存。即使official examples似乎也会分配arbitrarily large个内存块。

考虑以下结构:

managed_shared_memory

我最初的反应是必要的大小是8个字节,或// Example: simple struct with two 4-byte fields struct Point2D { int x, y; }; 。当我尝试构造一个对象时,这会失败,在运行时给出了seg-fault。

sizeof(Point2D)

什么读/写操作导致seg-faults?堆栈操作?临时分配// BAD: 8 bytes is nowhere near enough memory allocated. managed_shared_memory segment(create_only, "My shared memory", sizeof(Point2D)); ?分配共享内存时需要多少开销?

通过反复试验,我发现将大小乘以4可以适用于上述结构,但是当我开始向segment.construct()添加更多字段时会崩溃。所以,这是一个糟糕的黑客。

有些人可能会认为现代个人电脑中的“记忆力很便宜”,但我不同意这种理念,不喜欢分配比我需要的更多,如果我可以避免它。我昨天在Boost文档中挖了一遍,找不到任何建议。这是今天要学习新知识的东西!

2 个答案:

答案 0 :(得分:8)

来自文档的this paragraph

  

内存算法是一个对象   放在a的第一个字节中   共享内存/内存映射文件   段。

内存段的布局:

 ____________ __________ ____________________________________________  
|            |          |                                            | 
|   memory   | reserved |  The memory algorithm will return portions | 
| algorithm  |          |  of the rest of the segment.               | 
|____________|__________|____________________________________________| 

库在段的开头有一个额外的内存开销,因此占用了所请求大小的几个字节。根据{{​​3}}和this post,无法确定此确切的附加字节数:

  

你无法计算它,因为那里   是内存分配bookeeping和   变化的碎片问题   运行时取决于你的   分配/解除分配模式。和   共享内存由页面分配   通过操作系统(Linux on 64k上的4K)   windows),所以任何分配都会   在实践中分配四舍五入到   页:

    managed_shared_memory segment(create_only, "name", 20);
     

会浪费相同的记忆:

    managed_shared_memory segment(create_only, "name", 4096);

答案 1 :(得分:2)

使用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]();