首页 > 编程语言 > 详细

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

时间:2015-03-27 08:51:19      阅读:282      评论:0      收藏:0      [点我收藏+]

文章 进行转载,再次感谢

概述

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

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

原文:http://blog.csdn.net/xiaorenwuzyh/article/details/44658745

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!