简体   繁体   English

C++中的共享内存对齐

[英]Shared memory alignment in C++

Is there any alignment for allocated shared memory?分配的共享内存是否有任何对齐? If yes, is it for all operating system?如果是,是否适用于所有操作系统?

For example, allocating shared memory in boost:比如在boost中分配共享内存:

boost::interprocess::shared_memory_object* segment =
    new boost::interprocess::shared_memory_object(
        boost::interprocess::create_only,
        "name",
        boost::interprocess::read_write);

segment->truncate(10000);

The shared/virtual memory system allocates and maps memory pages and is aligned by the page size.共享/虚拟内存系统分配和映射内存页面,并按页面大小对齐。 See a list of pages sizeshere . 在此处查看页面大小列表。 Page size is CPU and OS specific.页面大小是特定于 CPU 和操作系统的。 I am not aware of modern CPUs that use page sizes smaller than 4kB.我不知道使用小于 4kB 的页面大小的现代 CPU。

On a POSIX system you can find out the page size using sysconf(_SC_PAGESIZE) .在 POSIX 系统上,您可以使用sysconf(_SC_PAGESIZE)找出页面大小。 In case when huge pages are in use, this call returns the smallest page size.如果正在使用大页面,则此调用将返回最小的页面大小。

There is no shred memory in C++ itself. C++ 本身没有碎片内存。 There are various extensions.有各种扩展。 The raw ones return page aligned blocks, but your wrapper might add a sub-block allocation system to them.原始的返回页面对齐的块,但您的包装器可能会向它们添加子块分配系统。

If you have a block of memory you can find an aligned pointer within the block, either manually by messing with bits (non portable), or using std::align .如果您有一块内存,您可以在该块内找到一个对齐的指针,可以手动通过混淆位(不可移植)或使用std::align It is designed to make it pretty easy to "peel" off aligned sub blocks from an unaligned block.它旨在使从未对齐​​的块中“剥离”对齐的子块变得非常容易。

struct aligned_peeler {
  void* raw=nullptr;
  std::size_t size=0;
  void* operator*( std::size_t align, std::size_t amt ){
    return std::align(align, amt, raw, size);
  }
};

Now an aligned_peeler can be handed a block, and you can ask for aligned pieces from it.现在可以将一个块交给aligned_peeler ,您可以从中请求对齐的块。 It will fail and return nullptr when it runs out of room.当它用完空间时,它将失败并返回 nullptr。

Turning this into a real free store is a lot of work, but I'd guess boost has at least one allocator that can be fed shared memory pages as a source.把它变成一个真正的免费存储需要很多工作,但我猜boost至少有一个分配器可以作为源提供共享内存页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM