Go語言中使用 buffered channel 實現(xiàn)線程安全的 pool
概述
我們已經(jīng)知道 Go 語言提供了 sync.Pool,但是做的不怎么好,所以有必要自己來實現(xiàn)一個 pool。
給我看代碼:
type Pool struct {
pool chan *Client
}
// 創(chuàng)建一個新的 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...
}
}
總結(jié)
現(xiàn)在不要使用 sync.Pool