1. 程式人生 > 其它 >golang sync.pool

golang sync.pool

技術標籤:golanggolang

直接上程式碼:


package work
 
import (
	"fmt"
	"sync"
)
func Cpool() {
	p:=&sync.Pool{
		New: func() interface{}{
			return 0
		},
	}
	info := make(map[string]string)
	buf := make([]string,1)
	buf = append(buf,"charlie")
	buf = append(buf,"bennie"
) info["name"] = "charlie" info["age"] = "30" p.Put("jiangzhou") p.Put(123456) p.Put("charlie") p.Put(info) p.Put(buf) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(
p.Get())//這裡已經空了 取出的是0 fmt.Println(p.Get()) fmt.Println(p.Get()) p.Put("jiangzhou") p.Put(123456) p.Put("charlie") p.Put(info) p.Put(buf) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get()) fmt.Println(p.Get())//這裡已經空了 取出的是0
fmt.Println(p.Get()) fmt.Println(p.Get()) }

列印結果:

jiangzhou
[ charlie bennie]
map[name:charlie age:30]
charlie
123456
0
0
0
jiangzhou
[ charlie bennie]
map[name:charlie age:30]
charlie
123456
0
0
0

總結:

1.sync.Pool結構體裡面包含一個匿名的new作用的函式,接受interface{}
2.put()放入,get()取出,取出是無序的,當pool裡面為nil的時候,get()返回0
3.pool裡面不要求型別統一