首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

用boost的Memory Mapped File怎么规避alloc后当机造成的内存泄露

2012-05-24 
用boost的Memory Mapped File如何规避alloc后当机造成的内存泄露?刚学boost的managed_mapped_file,用这个

用boost的Memory Mapped File如何规避alloc后当机造成的内存泄露?
刚学boost的managed_mapped_file,用这个建立内存映射文件,然后创建了std兼容的allocator,传给map容器。让map容器用这个managed_mapped_file申请内存,这样2个进程的map可以完全同步。

但想到了一个问题,假设map在添加键值途中,它内部刚alloc了一个内存就停电或当机了,那么这片内存岂不是永远回收不了了?除非整个映射文件删除重新来,但架构不允许这么做。

这种问题要如何解决呢?

为了便于理解,示例大致代码:
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>

typedef managed_mapped_file::segment_manager segment_manager_t;
typedef allocator<void, segment_manager_t> void_allocator;

//让字符串也使用内存映射文件申请内存
typedef allocator<char, segment_manager_t> char_allocator;
typedef basic_string<char, std::char_traits<char>, char_allocator> char_string;

//让map使用内存映射文件申请内存
typedef allocator<std::pair<const char_string, int>, segment_manager_t> map_value_type_allocator;
map< char_string, int, std::less<char_string>, map_value_type_allocator> string_map_type;


int main ()
{
  //Create shared memory
  managed_shared_memory segment(create_only,"MySharedMemory", 65536);

  //An allocator convertible to any allocator<T, segment_manager_t> type
  void_allocator alloc_inst (segment.get_segment_manager());

  string_map_type *mymap = segment.construct<string_map_type>
  //(object name), (first ctor parameter, second ctor parameter)
  ("MyMap")(std::less<char_string>(), alloc_inst);

  char_string key_object("1234567890", alloc_inst);
  //在这里停电
  //key_object字符串实际上已经申请到映射文件中了,如果这里停电,这个内存将永远无法回收
  mymap->insert(std::pair<const char_string, int>(key_object, 1));
  //如果在insert途中停电,不知道map整个类会不会损坏或者其他问题。

}

还请有经验的人指导下。



[解决办法]
停电了或当机内存肯定不用清除了,关键是内存映射文件是不是写到磁盘文件中,估计可以开机文件检查时恢复的。
[解决办法]
这个库在windows上的稳定性不够牢固,特别是长时间运行的程序。
[解决办法]

探讨
对,关键就是映射文件写到了磁盘里,我检查过了,开机读取这个文件那么这个区域的内存就泄露了。

to:icosagon
具体怎么说?又没相关讨论的地址,谢谢

[解决办法]
探讨
就是说,你对内存alloc,windows会立即写入到文件,假设这时候停电没有释放内存,那么下次重新映射这个文件后,程序并不知道这片内存区域没有释放,而windows却认为这片内存区域已用,也就是说,这个映射文件中的内存泄露了。

[解决办法]
设置一个标志区域,标志区域可以在同一个文件内,也可以在不同文件中,写的时候先写这个标志区域,估计也就微秒级的时间,如果连这个都碰到了,那也没话可说了。

热点排行