C++標(biāo)準(zhǔn)庫如何實(shí)現(xiàn)共享內(nèi)存介紹
初次使用C++標(biāo)準(zhǔn)庫實(shí)現(xiàn)共享內(nèi)存的管理時(shí),Vector每次分配內(nèi)存?zhèn)€數(shù)不固定,回收也不固定,這樣的話,程序還需要繼續(xù)完善,下面就隨本文的講述來讓大家進(jìn)一步的了解C++中的C++標(biāo)準(zhǔn)庫。
內(nèi)存池管理程序源碼如下:
- #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; /* 共享內(nèi)存鍵值 */
- int iShmID; /* iShmKey對(duì)應(yīng)的shmid */
- int iSemKey; /* 鎖信號(hào)鍵值 */
- int iSemID; /* 鎖信號(hào)標(biāo)識(shí) */
- int iTotalsize; /* 容器總?cè)萘?nbsp;*/
- void* pStartall; /* 共享內(nèi)存自身地址 */
- char* pStartfree; /* 自由空間的開始地址*/
- char* pEndfree; /* 自由空間的結(jié)束地址*/
- int iUseNum[NODENUMS];
- /*用來存放free_list中節(jié)點(diǎn)的size*/
- short sFreelistIndex[NODENUMS];
- /*存放分配內(nèi)存節(jié)點(diǎn)的鏈表*/
- 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;
- };
以上程序只要稍微修改,就可以實(shí)現(xiàn)共享內(nèi)存的管理,可以方便的使用C++標(biāo)準(zhǔn)庫提供的容器。加上信號(hào)量的鎖機(jī)制。以上為了學(xué)習(xí)而改寫的SGI的stl二級(jí)分配算法實(shí)現(xiàn)的。以上代碼存在一定的局限性。
我另外完整實(shí)現(xiàn)了共享內(nèi)存管理的STL標(biāo)準(zhǔn)的alloctor程序,使用posix信號(hào)量加鎖。目前應(yīng)用在aix的xlC編譯環(huán)境下。因?yàn)樵创a涉及公司的商業(yè)秘密,所以不能公開。但基本上以上源碼已經(jīng)體現(xiàn)了自己管理內(nèi)存的完整思路,供這方面需求的朋友一起學(xué)習(xí)研究用。
【編輯推薦】