Memory pool management of objects of size

xiaoxiao2021-03-06  65

This is a simple memory management class I wrote, mainly in: If there is a small number of other objects to frequent NEW and DELETE, in order to prevent a large amount of memory fragmentation and efficiency, consider using the following memory management. class. Next article, I will introduce how to use this class #1ndef _Mempool_h # define _Mempool_h / ***************************************** ******************************************* CREATED: 2004/11/29 create: 29:11: 2004 16:02 FILENAME: ../Memory pool / test / cmempool.h file path: ../memory pool / test file base: cmempool file extra: h author: david purpose: Equivalent small object If frequent dynamic application With the release (EG: S ERVER), it will inevitably lead to a large amount of memory fragments, so when the system is running for a long time, it will not be able to share memory because of a large number of memory fragments, so our software will change Unstable, and frequent NEW and Delete will result in low efficiency, so you need to have your own memory management. The following classes are a simple memory management. *********************************************************** ****************** /

#include "lock.h"

Template struct mem_pool_node {union {char obj [sizeof (cnode)]; MEM_POOL_NODE * m_PNEXT;};

Template class cmempool {type> * MEM_POOL_NODE_TYPE; public: cmempool () {m_plistfreepool = null; m_ninuse = 0; m_nfree = 0;};

Virtual ~ cmempool () {mem_pool_node_type pprenode = null; mem_pool_node_type pnode = null;

M_Lock.lock (); pprenode = m_plistfreepool; pnode = m_plistfreepool; while (null! = pnode) {pPRenode = pnode; pnode = pnode-> m_pnext;

DELETE PPRENODE; PPRENODE = NULL;} m_lock.unlock ();}; cnode * allocate () {void * p = null; mem_pool_node_type pnode = null;

IF (null == m_plistfreepool) {Try {p = (:: operator new));} catch (...) {if (p! = null) {:: operator delete ((cnode *) (p)); p = null;}

Return NULL;

M_lock.lock (); m_ninuse ; m_lock.unlock ();} else {m_lock.lock (); pnode = m_plistfreepool; m_plistfreepool = m_plistfreepool-> m_pnext; p = pnode;

m_nfree-; m_ninuse ; m_lock.unlock ();}

Return static_cast (p);}; void release (void * p) {if (null == p) {return;

m_Lock.Lock (); if (NULL == m_pListFreePool) {m_pListFreePool = static_cast (p); m_pListFreePool-> m_pNext = NULL;} else {(static_cast (p)) -> m_pNext = m_pListFreePool; m_pListFreePool = static_cast (p);

M_ninuse -; m_nfree ; m_lock.unlock ();}; void getInfo (int & INT & INUSE = m_ninuse; free = m_nfree;}; private: clock m_lock;

INT M_NINUSE; int m_nfree;

MEM_POOL_NODE_TYPE M_PLISTFREEPOOL;

#ENDIF

转载请注明原文地址:https://www.9cbs.com/read-86659.html

New Post(0)