华域联盟 Golang Go语言中使用 buffered channel 实现线程安全的 pool

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

转载请保留出处和原文链接:https://www.cnhackhy.com/109855.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Go语言struct类型详解

Go语言命令行操作命令详细介绍

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们