概述
我們已經(jīng)知道 Go 語言提供了 sync.Pool,但是做的不怎么好,所以有必要自己來實現(xiàn)一個 pool。
給我看代碼:
// 創(chuàng)建一個新的 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...
}
}
總結(jié)
現(xiàn)在不要使用 sync.Pool
標(biāo)簽:本溪 湘潭 九江 晉城 深圳 運城 楚雄 喀什
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Go語言中使用 buffered channel 實現(xiàn)線程安全的 pool》,本文關(guān)鍵詞 語,言中,使用,buffered,channel,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。