您的位置:首页 > Web前端

Golang -- 使用 Bufferd channel 实现 线程安全的 pool

2015-03-26 23:06 519 查看
文章 进行转载,再次感谢

概述

我们知道,Go 语言已经提供了
sync.Pool
,但是做的不怎么好,所以有必要来实现一个 Pool

代码

type Pool struct {
pool chan *Client
}

// Create a new Pool
func NewPool(max int) *Pool{
return &Pool{
pool: make(chan *Client, max)
}
}

// Get a Client from Pool
func (p *Pool) Borrow() *Client {
var cl *Client
select {
case cl = <-p.pool:
default:
c1 = newClient()
}
return cl
}

// Return the Cliet to the pool
func (p *Pool) Return(cl *Client){
select {
case p.pool<- cl:
default:
// let it go, let it go....
}
}


现在是 Golang1.4了,
sync.Pool
还是不可以用吗?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: