主頁 > 知識(shí)庫 > Go語言中使用 buffered channel 實(shí)現(xiàn)線程安全的 pool

Go語言中使用 buffered channel 實(shí)現(xiàn)線程安全的 pool

熱門標(biāo)簽:百度競價(jià)排名 網(wǎng)站排名優(yōu)化 Linux服務(wù)器 呼叫中心市場需求 服務(wù)外包 鐵路電話系統(tǒng) 地方門戶網(wǎng)站 AI電銷

概述

我們已經(jīng)知道 Go 語言提供了 sync.Pool,但是做的不怎么好,所以有必要自己來實(shí)現(xiàn)一個(gè) pool。

給我看代碼:

復(fù)制代碼 代碼如下:

type Pool struct {
  pool chan *Client
}

// 創(chuàng)建一個(gè)新的 pool
func NewPool(max int) *Pool {
  return Pool{
    pool: make(chan *Client, max),
  }
}

// 從 pool 里借一個(gè) 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...
  }
}

總結(jié)

現(xiàn)在不要使用 sync.Pool

您可能感興趣的文章:
  • go原生庫的中bytes.Buffer用法
  • C#語言使用gRPC、protobuf(Google Protocol Buffers)實(shí)現(xiàn)文件傳輸功能
  • 詳解Django-channels 實(shí)現(xiàn)WebSocket實(shí)例
  • Django使用Channels實(shí)現(xiàn)WebSocket的方法
  • Django Channels 實(shí)現(xiàn)點(diǎn)對點(diǎn)實(shí)時(shí)聊天和消息推送功能
  • 再次探討go實(shí)現(xiàn)無限 buffer 的 channel方法

標(biāo)簽:銅川 湖南 衡水 黃山 仙桃 湘潭 蘭州 崇左

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Go語言中使用 buffered channel 實(shí)現(xiàn)線程安全的 pool》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266