• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Gosync.Pool缓存池

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

sync.Pool 对象获取

sync.Pool 的缓存跟 Processor(处理器) 有关系,Processor 中包含了私有对象(只有一个,协程安全)和共享池(协程不安全)

  • 尝试从私有对象获取
  • 私有对象不存在,尝试从当前 Processor 的共享池获取
  • 如果当前 Processor 共享池也是空的,那么就尝试去其他 Processor 的共享池获取
  • 如果所有子池都是空的,最后就用用户指定的 New 函数产生一个新的对象返回

sync.Pool 对象放回

  • 如果私有对象不存在则保存为私有对象
  • 如果私有对象存在,放入当前 Processor 子池的共享池

使用sync.Pool

pool := &sync.Pool{
    New: func() interface{} {
        return 0	
    },
}
arry := pool.Get().(int)
    ...
pool.Put(10)

sync.Pool 对象的生命周期

  • GC 会清除 sync.Pool 缓存的私有对象,共享池的对象还会存在,具体看下面示例
  • 私有对象的缓存有效期为下一次 GC 之前

所以 sync.Pool 是不能用来作为对象池的

sync.Pool 示例

package obj_cache

import (
	"fmt"
	"runtime"
	"sync"
	"testing"
)

// 在 win10 上测试这段程序发现,GC 有的时候没效果,大多数情况下会回收私有对象
func TestSyncPool(t *testing.T) {
	pool := &sync.Pool{
		// new 的对象不会放入私有对象或共享池
		New: func() interface{} {
			fmt.Println("Create a new object.")
			return 100
		},
	}
	v := pool.Get().(int) // 第一次获取,私有对象和共享池中都没有,会 New 一个 100
	fmt.Println(v)
	pool.Put(3) // 私有对象为空,所以 3 会被放入私有对象
	pool.Put(4) // 私有对象非空,放入共享池
	runtime.GC() // GC 会清楚sync.pool 中缓存的私有对象,共享池中的对象还是存在的
	v1, _ := pool.Get().(int)
	v2, _ := pool.Get().(int)
	v3, _ := pool.Get().(int)
	fmt.Println(v1)
	fmt.Println(v2)
	fmt.Println(v3)
}

func TestSyncPoolInMultiGroutine(t *testing.T)  {
	pool := &sync.Pool{
		New: func() interface{} {
			fmt.Println("Create a new object.")
			return 10
		},
	}
	pool.Put(100)
	pool.Put(100)
	pool.Put(100)

	var wg sync.WaitGroup
	for i := 0; i<10; i++{
		wg.Add(1)
		go func(id int) {
			fmt.Println(pool.Get())
			wg.Done()
		}(i)
	}
	wg.Wait()
}

sync.Pool 总结

  • 适合于通过复用,降低复杂对象的创建和GC代价
  • 协程安全,会有锁的开销
  • 生命周期受 GC 影响,不适合于做连接池等需要自己管理生命周期的资源的池化

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go语言简介发布时间:2022-07-10
下一篇:
028Go语言标准库之context发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap