Go语言中使用 buffered channel 实现线程安全的 pool

发布时间:2022-04-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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全部内容,希望文章能够帮你解决Go语言中使用 buffered channel 实现线程安全的 pool所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。