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

(编辑:jimmy 日期: 2025/2/22 浏览:2)

概述

我们已经知道 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

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。