欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-26 13:43:13
概述 我们已经知道 go 语言提供了 sync.pool,但是做的不怎么好,所以有必要自己来实现一个 pool。 给我看代码: 复制代码 代码如下: type po...

概述

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