微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

文章 进行转载,再次感谢

概述

我们知道,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还是不可以用吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐