package main import ( "fmt" "strconv" "sync" ) //在go中,原生的池化数据结构为sync.Pool, 有三个方法: //New字段为一个方法,定义为func() interface{}, 在新建Pool时,定义好New字段,以供后续从池中获取对象时,如果当前池中无对象,则使用此方法来新建对象。 //Get()方法:从池中获取对象 //Put(x interface{})方法:将对象放入池中 var pool2 *sync.Pool type Person2 struct { Name string Age int } func init() { pool2 = &sync.Pool{ New: func() interface{} { fmt.Println("creating a new person") return new(Person2) }, } //初始化时创建10个对象 for i := 0; i < 10; i++ { pool2.Put(&Person2{"name_" + strconv.Itoa(i), i}) } } func main() { for i := 0; i < 9; i++ { fmt.Println("Get object from pool again:", pool2.Get().(*Person2)) } p := pool2.Get().(*Person2) fmt.Println("Get object from pool again:", p) pool2.Put(p) //用完之后放回 fmt.Println("Get object from pool again:", pool2.Get().(*Person2)) fmt.Println("Get object from pool again:", pool2.Get().(*Person2)) } //Get object from pool again: &{name_0 0} //Get object from pool again: &{name_9 9} //Get object from pool again: &{name_8 8} //Get object from pool again: &{name_7 7} //Get object from pool again: &{name_6 6} //Get object from pool again: &{name_5 5} //Get object from pool again: &{name_4 4} //Get object from pool again: &{name_3 3} //Get object from pool again: &{name_2 2} //Get object from pool again: &{name_1 1} //Get object from pool again: &{name_1 1} //creating a new person //Get object from pool again: &{ 0}
go 的 Pool池对象-sync.Pool
Golang
2023-04-10
admin
229
309
如果文章对您有帮助,点击下方的广告,支持一下作者吧!
转载必须注明出处: