对象池sync.pool使用

对象池区别与其他的连接池,它只能存放临时的变量,用来缓解GC的处理压力。

用途:

1.sync.Pool是一个可以存或取的临时对象集合
2.sync.Pool可以安全被多个线程同时使用,保证线程安全
注意、注意、注意,sync.Pool中保存的任何项都可能随时不做通知的释放掉,所以不适合用于像socket长连接或数据库连接池。
sync.Pool主要用途是增加临时对象的重用率,减少GC负担。
 

type Pool struct {

        // New optionally specifies a function to generate
        // a value when Get would otherwise return nil.
        // It may not be changed concurrently with calls to Get.
        New func() interface{}
        // contains filtered or unexported fields
}

//从 Pool 中获取元素,元素数量 -1,当 Pool 中没有元素时,会调用 New 生成元素,新元素不会放入 Pool 中,若 New 未定义,则返回 nil
func (p *Pool) Get() interface{}

//往 Pool 中添加元素 x
func (p *Pool) Put(x interface{})

type Foo struct {
	count int
}

var pool *sync.Pool

func init() {
	pool = &sync.Pool{
		New: func() interface{} {
			return []*Foo{}
		},
	}
}

func main() {
	//放十个对象进入
	for i := 0; i < 10; i++ {
		req := pool.Get().([]*Foo) //获取池里面的之前数据
		dd := &Foo{
			count: i,
		}
		req = append(req, dd) //组装好的数据
		pool.Put(req)         //放入池中
	}
	//再放十个对象进入
	for i := 10; i < 20; i++ {
		req := pool.Get().([]*Foo)
		dd := &Foo{
			count: i,
		}
		req = append(req, dd)
		pool.Put(req)
	}
	res := pool.Get().([]*Foo)
	for _, v := range res {
		fmt.Println("====res:", v.count)
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值