一種記憶體池的實現方法

2022-04-06 18:41:12 字數 1488 閱讀 8684

大圖:這裡使用python的**,來解釋

# size 是呼叫者意欲分配的記憶體大小

def allocate(size):

# 如果這裡分配的大小大於了最大快取的size:直接通過malloc/operatornew 申請

if size > max_pooled_size:

use_malloc_or_operator_new(size);

return;

# 將意欲分配的size提公升到匹配的size

size = improvesize(size)

# 獲取對應size大小的index

index = getindexbysize(size)

# 如果記憶體池中有空閒該大小的記憶體

if not memory_pool[index].empty():

# 返回該位址

return memory_pool[index].pop_back();

else:

use_malloc_or_operator_new(size)

釋放記憶體的過程,重點分支有兩個:乙個是分配的大小大於32mb,那麼直接釋放,如果小於32mb,那麼應該返回到記憶體池中,但也不是無條件的返回到記憶體池,當記憶體池中該size的記憶體過多時,也應該釋放。

def free(p):

# 該block太大,那麼就應該直接釋放

if blockislargethanmaxsize(p):

use_free_or_operator_delete(p);

else if currentblockcachednummorethanmax():

use_free_or_operator_delete(p);

else:

memory_pool[index].push_back(p)

cached_num++;

這種實現,對於每一刻分配的記憶體,都有乙個頭,來表示上下文,比如當前分配的大小,在記憶體池中idx大小,這樣在是釋放的時候,根據頭的資訊,能夠方便是釋放或快取到記憶體池中。

// 和 operator delete

operator delete(block);

atomicincrement(&m_dwdeletecount);

記憶體池的一種實現

include include include include include const.h include utilityfunc.h include hashtable.h include logmsg.h define system page size 4096 define default...

一種巧妙的記憶體池演算法 HeapBlock

在乙個簡單的gui庫中看到的演算法,非常巧妙,適用於需要頻繁分配和釋放相同大小資料塊的情況,如gui庫中的視窗結構,socket結構等,演算法額外開支極小。cpp view plain copy print?typedef dword hblockheap typedef unsigned char...

一種定位記憶體洩露的方法(Linux)

本文是 一種定位記憶體洩露的方法 solaris 對應的 linux 版本,偵錯程式使用 gdb。主要介紹例項部分。其他請見 一種定位記憶體洩露的方法 solaris 模擬 new失敗的程式 include class abc int i int j void f throw std bad all...