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
相关文章
CentOS 32 bit安装golang 1.7的步骤详解
Go是Google开发的一种编译型,并发型,并具有垃圾回收功能的编程语言。在发布了6个rc版本之后,Go 1.7终于正式发布了。本文主要介绍了在CentOS 32 bit安装golang 1.7的步骤,文中给出了详细的步骤,相信对大家的学习和理解具有一定的参考借鉴价值,下面来一起看看吧。2016-12-12golang提示dial tcp 172 .217.163.49:443: connectex: A con
这篇文章主要为大家介绍了golang提示dial tcp 172 .217.163.49:443: connectex: A connection attempt failed解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-07-07Go语言动态并发控制sync.WaitGroup的灵活运用示例详解
本文将讲解 sync.WaitGroup 的使用方法、原理以及在实际项目中的应用场景,用清晰的代码示例和详细的注释,助力读者掌握并发编程中等待组的使用技巧2023-11-11
最新评论