提升包含自定义类的shared_memory deque容器

时间:2013-07-11 20:08:17

标签: c++ boost shared-memory

我正在尝试让两个进程访问同一个共享内存。我有process1用my_custom_class *创建一个deque。 my_custom_class包含一些整数。

typedef boost::interprocess::allocator<my_custom_frame*, boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;
typedef boost::interprocess::deque<my_custom_frame*, ShmemAllocator> VideoDeque;

boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only, "MySharedMemory", 100000000);
video_deque = segment.construct<VideoDeque>("VideoDeque")(alloc_inst);

使用自定义分配器在共享内存中创建deque后,我使用共享内存上的allocate方法创建my_custom_frame。我首先为my_custom_frame的大小分配内存,然后使用placement new()我在那里创建一个my_custom_frame对象。

temp1 = segment.allocate(sizeof(my_custom_frame));
frame1 = (my_custom_frame*) new (temp1) my_custom_frame();

然后我通过在frame1上调用copy_dframe_to_cf方法在my_custom_frame中设置整数。然后我将frame1推送到video_deque。此时,如果我在代码框架中设置了一个断点,则所有整数变量都设置正确。

frame1->copy_dframe_to_cf(video_frames[0].get());
video_deque->push_back(frame1);

在process2中,我打开共享内存并找到我的双端队列。

boost::interprocess::managed_shared_memory segment(boost::interprocess::open_only, "MySharedMemory");

//Find the vector using the c-string name
VideoDeque* my_video_deque = segment.find<VideoDeque>("VideoDeque").first;

然后我从my_video_deque获取my_custom_frame。

typedef std::deque<my_custom_frame*> MyFrameQueue;
MyFrameQueue my_video_frames;

my_video_frames.push_back(my_video_deque->front());
my_custom_frame *pFrame;
pFrame = my_video_frames[0];

此时,当我查看pFrame中的值时,它们都被设置为0. pFrame指向的内存地址与我在process1中放置的deque相同,所以我想我正在访问相同的正确内存位置但由于某种原因正在重置值。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

将原始指针存储在共享内存中是一个禁忌:共享内存段不太可能映射到所有进程中的同一地址。您需要使用offset_ptr per the boost.interprocess documentation或只是按值而不是指针存储所有内容。

即,

typedef boost::interprocess::deque<my_custom_frame, ShmemAllocator> VideoDeque;

typedef boost::interprocess::deque<boost::interprocess::offset_ptr<my_custom_frame>, ShmemAllocator> VideoDeque;