温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中怎么实现共享内存

发布时间:2021-07-23 16:35:38 来源:亿速云 阅读:178 作者:Leah 栏目:编程语言

C++中怎么实现共享内存,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

初次使用C++标准库实现共享内存的管理时,Vector每次分配内存个数不固定,回收也不固定,这样的话,程序还需要继续完善,下面就随本文的讲述来让大家进一步的了解C++中的C++标准库。

内存池管理程序源码如下:

#ifndef MY_ALLOCATOR_H_   #define MY_ALLOCATOR_H_   #include "stdafx.h"   #include <limits>   #include <iostream>   namespace happyever    {     enum { NODENUMS = 2 };     union _Obj      {       union _Obj* M_free_list_link;       char M_client_data[1];         } ;     typedef union _Obj Obj;     struct _Cookie     {       int iShmKey;        /* 共享内存键值 */       int iShmID;         /* iShmKey对应的shmid */       int iSemKey;        /* 锁信号键值 */       int iSemID;         /* 锁信号标识 */       int iTotalsize;    /* 容器总容量 */       void* pStartall;   /* 共享内存自身地址 */       char* pStartfree;  /* 自由空间的开始地址*/       char* pEndfree;    /* 自由空间的结束地址*/       int iUseNum[NODENUMS];       /*用来存放free_list中节点的size*/       short sFreelistIndex[NODENUMS];       /*存放分配内存节点的链表*/       Obj* uFreelist[NODENUMS];     };     typedef struct _Cookie Cookie;     //Obj;     //Cookie;     static Cookie *pHead = NULL;     template <class T>     class MyAlloc      {     private:       static const int ALIGN = sizeof(Obj);       int round_up(int bytes);       int freelist_index(int bytes);       int freelist_getindex(int bytes);       char* chunk_alloc(int size, int *nobjs);       void* refill(int num,int n);     public:       // type definitions       typedef T        value_type;       typedef T*       pointer;       typedef const T* const_pointer;       typedef T&       reference;       typedef const T& const_reference;       typedef std::size_t    size_type;       typedef std::ptrdiff_t difference_type;       template <class U>       struct rebind        {         typedef MyAlloc<U> other;       };

以上程序只要稍微修改,就可以实现共享内存的管理,可以方便的使用C++标准库提供的容器。加上信号量的锁机制。以上为了学习而改写的SGI的stl二级分配算法实现的。以上代码存在一定的局限性。

看完上述内容,你们掌握C++中怎么实现共享内存的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI