【Boost】Interprocess - 共享内存、文件映射介绍

本文介绍了Boost库中的Interprocess模块,通过示例展示了如何使用基于文件映射的Map和基于共享内存的Map及Vector。讨论了共享内存机制的生命周期,包括进程持久性、内核持久性和文件系统持久性,以及Boost.Interprocess在不同平台间的移植性问题。
摘要由CSDN通过智能技术生成


一、用法介绍


      通过Interprocess,可以实现在共享内存、文件映射中保存vector、map等STL对象,并且可以使用自定义的类,官方文档介绍的也很详细了,下面是几个精简的示例。

  • 示例:基于文件映射的Map使用
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <cstdlib> //std::system
#include <utility>
#include <stdio.h>
#include <stdlib.h>
#include <exception>
#include <sys/mman.h>
#include <sys/stat.h>        /*  For mode constants */
#include <fcntl.h>           /*  For O_* constants */
#include <string>

using namespace boost::interprocess;
using std::string;

class Item
{
    public:
    Item(){}
    ~Item(){}

    int id;
    int size;
    string name;
};

typedef int KeyType;
typedef Item MappedType;
typedef std::pair<const int, Item> ValueType;

typedef allocator<ValueType, managed_mapped_file::segment_manager> ShmemAllocator;

typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MyMap;

int main()
{
    try {
        // init
        managed_mapped_file segment(open_or_create, "SharedMemory", 65536);


        MyMap *mymap = segment.find<MyMap>("MyMap").first;
        if (mymap == NULL)
        {
            const ShmemAllocator alloc_inst (segment.get_segment_manager());

            mymap = segment.construct<MyMap>("MyMap") (std::less<int>(), alloc_inst);

        }

        Item v;
        for(int i = 0; i < 100; ++i){
            v.id = i;
            mymap->insert(std::pair<const int, Item>(i, (Item)v));
        }

        for (MyMap::iterator it = mymap->begin(); it != mymap->end(); it++) {
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值