Arbitrary size allocated memory pool implementation

xiaoxiao2021-03-06  83

Recently, I have written multimedia flow, I found that I have to distribute memory. If I use New to allocate speed, it will be very slow, so I have made a memory pool. But if you want to develop any size allocated memory pool is very difficult, and you can't guarantee that there is New's speed, the memory pool you see online is generally allocated. Although the memory pool allocated by any size is difficult to achieve, it is easy to change under certain special conditions. For example, if the order of memory release is released in the order of assignments, this situation is very useful if the queue is used to store large amounts of data.

Implementing this memory pool only requires a larger buffer and two pointers, a location indicating the allocated spatial head, a representation that has been allocated. If there is no sufficient space without a sufficient space to use New to allocate.

Distribution implementation:

/ *

* @Func: alloc

* @Brief: Assign space for NSIZE Size

* @Param: [in] Ulong nsize to assign the space size

* @Ret: The start address of the space allocated by PVOID

* /

PVOID CRANDOMMEMPOOL :: Alloc (Ulong nsize)

{

Cautolock Lock (& ​​M_LOCK);

PBYTE PPTR = NULL;

IF (m_ntail> m_nheader || (m_ntail == m_nheader && m_npoolleft> 0))))

{

IF (m_npoolsize - m_ntail> = nsize)

{

PPTR = M_PPOOL M_NTAIL;

m_ntail = nsize;

} else if (m_nheader> = nsize)

{

PPTR = M_PPOOL;

m_ntail = nsize;

}

} else if (m_ntail

{

IF (M_NHeader - M_ntail> = nsize)

{

PPTR = M_PPOOL M_NTAIL;

m_ntail = nsize;

}

}

IF (pptr == null)

{

Trace ("The Memory Pool Is Empty, Use New To Alloc / R / N");

Pptr = new byte [nsize];

Else

{

m_npoolleft - = nsize;

}

Return PPTR;

}

Release implementation:

/ *

* @Func: free

* @Brief: Release space, you must specify the size of the memory space

* @Param: [in] pvoid pptr memory space

* [In] ulong usize memory space size

* @Ret: void

* /

Void CrandommemPool :: Free (pvoid pptr, ulong nsize)

{

Cautolock Lock (& ​​M_LOCK);

IF (pptr> = m_ppool && pptr

{

IF (nsize> m_npoolsize - m_nheader)

m_nheader = 0;

/ / Must be recycled in order

Assert (pptr == m_ppool m_nheader);

m_nheader = nsize;

m_npoolleft = nsize;} else

{

delete [] PPTR;

PPTR = NULL;

}

}

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

New Post(0)