12

boost::interprocess我正在寻找一个明确的答案(如果确实存在的话),当通过's创建共享内存的静态块时应该分配多少内存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 文档,找不到任何建议。今天来学习新的东西!

4

2 回答 2

9

从文档的这一段

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

内存段布局:

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

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

您无法计算它,因为内存分配簿记和碎片问题会根据您的分配/释放模式在运行时发生变化。并且共享内存是由操作系统按页面分配的(Linux 上的 4K,Windows 上的 64k),因此实际上任何分配都将四舍五入分配到一个页面:

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

将浪费与以下相同的内存:

    managed_shared_memory segment(create_only, "name", 4096);
于 2010-11-12T16:54:07.863 回答
3

像使用操作系统的内存页面大小这样的东西是有效的。就我而言,这有效..

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]();
于 2011-01-12T01:33:23.897 回答