Go语言中使用 buffered channel 实现线程安全的 pool
概述
我们已经知道 Go 语言提供了 sync.Pool,但是做的不怎么好,所以有必要自己来实现一个 pool。
给我看代码:
代码如下:
type Pool struct {
pool chan *Client
}
// 创建一个新的 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
相关推荐
Hy 2020-11-13
xrslt 2020-11-06
yutian0 2020-10-26
杨树 2020-09-21
zhuyonge 2020-08-01
zhuyonge 2020-07-26
xiaoemo0 2020-07-18
fraternityjava 2020-06-26
luohui 2020-06-26
dxyadc 2020-06-26
luohui 2020-06-21
三动 2020-06-21
fengyun 2020-06-14
fraternityjava 2020-06-14
waitui00 2020-06-14
fraternityjava 2020-06-10
shayuchaor 2020-06-07