Go语言中使用 buffered channel 实现线程安全的 pool
2019/7/10 22:14:31
本文主要是介绍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
这篇关于Go语言中使用 buffered channel 实现线程安全的 pool的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-01got an unexpected keyword argument
- 2024-03-30维多利亚的秘密 golang入坑系统
- 2024-03-29mongodb sort by date
- 2024-03-29go swagger
- 2024-03-25mongodb cdc
- 2024-03-25how to use go in vscode
- 2024-03-22mongooseserverselectionerror: connect econnrefused ::1:27017
- 2024-03-21pymongo insert_many
- 2024-03-18projection mongodb
- 2024-03-14clickhouse-go