C++中怎么實(shí)現(xiàn)共享內(nèi)存,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
創(chuàng)新互聯(lián)公司從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元德州做網(wǎng)站,已為上家服務(wù),為德州各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:13518219792
初次使用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)的。以上代碼存在一定的局限性。
看完上述內(nèi)容,你們掌握C++中怎么實(shí)現(xiàn)共享內(nèi)存的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
分享名稱:C++中怎么實(shí)現(xiàn)共享內(nèi)存
轉(zhuǎn)載來源:http://muchs.cn/article38/pgodpp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、網(wǎng)站收錄、網(wǎng)站營銷、微信公眾號(hào)、移動(dòng)網(wǎng)站建設(shè)、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)