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
相关文章
Golang 使用os 库的 ReadFile() 读文件最佳实践
这篇文章主要介绍了Golang使用os库的ReadFile()读文件最佳实践,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下2022-09-09
Go语言中strings.HasPrefix、strings.Split、strings.SplitN() 函数
本文主要介绍了Go语言中strings.HasPrefix、strings.Split、strings.SplitN()函数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-08-08


最新评论