源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-08-30 08:20 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Go语言中使用 buffered channel 实现线程安全的 pool
[b]概述[/b] 我们已经知道 Go 语言提供了 sync.Pool,但是做的不怎么好,所以有必要自己来实现一个 pool。 给我看代码:
[u]复制代码[/u] 代码如下:
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...   } }
[b]总结[/b] 现在不要使用 sync.Pool
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部