考虑以下结构:
// Example: simple struct with two 4-byte fields struct Point2D { int x,y; };
我最初的反应是必要的大小是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));
什么读/写操作导致seg-fault?堆栈操作?在segment.construct()中临时分配?分配共享内存时需要多少开销?
通过反复尝试,我发现将大小乘以4可以适用于上述结构,但是当我开始向我的结构体添加更多的字段时,它会分崩离析.所以,这个恶作剧的恶作剧.
有些人可能认为现代电脑中的“记忆便宜”,但是我不同意这种观点,不喜欢分配比我需要的更多的东西,如果我可以避免.我昨天挖掘了Boost的文档,找不到任何建议.今天要学习新的东西!
解决方法
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:06001
will waste the same memory as:
06002