概述
我們已經知道 Go 語言提供了 sync.Pool,但是做的不怎么好,所以有必要自己來實現一個 pool。
給我看代碼:
// 創建一個新的 pool
func NewPool(max int) *Pool {
return &Pool{
pool: make(chan *Client, max),
}
}
// 從 pool 里借一個 Client
func (p *Pool) Borrow() *Client {
var cl *Client
select {
case cl = <-p.pool:
default:
cl = newClient()
}
return cl
}
// 還回去
func (p *Pool) Return(cl *Client) {
select {
case p.pool <- cl:
default:
// let it go, let it go...
}
}
總結
現在不要使用 sync.Pool
新聞熱點
疑難解答