首页 > 解决方案 > 在不取消映射所有指针的情况下增加 managed_shared_memory

问题描述

是否可以managed_shared_memory在不必重新分配使用allocateof 函数创建的指针地址的情况下增长segment_manager?理想情况下,我希望下面的代码能够安全地工作:

#include <boost/interprocess/managed_shared_memory.hpp>
#include <cstdlib> //std::system
#include <sstream>

int main (int argc, char *argv[])
{
   using namespace boost::interprocess;
   char *shptr;
   {
      //Create a managed shared memory segment
      managed_shared_memory segment(create_only, "MySharedMemory", 1024);

      //Allocate a portion of the segment (raw memory)
      managed_shared_memory::size_type free_memory = segment.get_free_memory();
      shptr = (char *) segment.allocate(1024/*bytes to allocate*/);
      shptr[1023] = 1;

      //Check invariant
      if(free_memory <= segment.get_free_memory())
         return 1;
   }
   {
       managed_shared_memory::grow("MySharedMemory", 500);

       //I don't intend to use the additionally allocated bytes in shptr because
       //it is not possible to support it from OS side.
       assert(shptr[1023] == 1);
       shptr[1023] = 2;

       managed_shared_memory segment(create_only, "MySharedMemory", 1024);

       //ability to allocate additional pointers without overriding
       //previous allocations
       char *shptr2 = (char *) segment.allocate(500/*bytes to allocate*/);
       assert(shptr[1023] == 2);
       shptr2[499] = 1;
   }

}

标签: c++boostshared-memoryboost-interprocess

解决方案


推荐阅读