golang实现一个简易的内存池

本文介绍了一种内存池管理方案的实现细节,包括如何通过 Go 语言创建和维护不同大小的内存池来提高程序效率。该方案能够根据所需内存大小动态调整并复用内存块,减少频繁分配与释放内存带来的开销。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package base

import (
	"fmt"
	m "math"
	"sync"
)

type Pool struct {
	sync.RWMutex
	pool    sync.Pool
	size    int
	idle    int32
	active  int32
	maxIdle int32
}

func NewPool(size int, maxIdle int) *Pool {
	return &Pool{
		size:    size,
		maxIdle: int32(maxIdle),
		pool: sync.Pool{New: func() any {
			arr := make([]byte, size)
			return &arr
		}},
	}
}

func (p *Pool) Get() *[]byte {
	p.Lock()
	defer p.Unlock()

	p.active++
	if p.idle > 0 {
		p.idle--
	}

	if p.active > 1000 {
		fmt.Printf("size=%d, idle=%d, active=%d\n", p.size, p.idle, p.active)
	}

	return p.pool.Get().(*[]byte)
}

func (p *Pool) Put(x any) {
	p.Lock()
	defer p.Unlock()

	p.active--
	if p.idle >= p.maxIdle {
		return
	}
	p.idle++
	p.pool.Put(x)
}

type MemoryPool struct {
	sync.RWMutex
	pools    []*Pool
	BaseSize int
	MaxIdle  int
}

func (p *MemoryPool) Get(size int) *[]byte {
	var bytes *[]byte
	p.RLock()
	if p.BaseSize <= 0 {
		p.RUnlock()
		return nil
	}

	for _, pool := range p.pools {
		if size <= pool.size {
			bytes = pool.Get()
			break
		}
	}
	p.RUnlock()

	if bytes != nil {
		return bytes
	}

	p.Lock()
	defer p.Unlock()

	var pool *Pool
	for _, pool = range p.pools {
		if size <= pool.size {
			return pool.Get()
		}
	}

	var maxSize int
	if pool != nil {
		maxSize = 2 * pool.size
	} else {
		maxSize = p.BaseSize
	}

	if size < p.BaseSize {
		size = p.BaseSize
	}

	for sz := maxSize; sz <= size; sz *= 2 {
		pool = NewPool(sz, p.MaxIdle)
		p.pools = append(p.pools, pool)
	}

	return pool.Get()
}

func (p *MemoryPool) Put(bytes *[]byte) {
	c := cap(*bytes)
	p.RLock()
	index := int(m.Log2(float64(c / p.BaseSize)))
	if index > len(p.pools) {
		p.RUnlock()
		return
	}
	pool := p.pools[index]
	p.RUnlock()
	pool.Put(bytes)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值