Last active
June 19, 2018 09:43
-
-
Save kamal-github/57a3d430a58bdc9ed2e39dd5ff2fc08c to your computer and use it in GitHub Desktop.
Pool implementation using buffered channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pool holds Clients. | |
type Pool struct { | |
pool chan *Client | |
} | |
// NewPool creates a new pool of Clients. | |
func NewPool(max int) *Pool { | |
return &Pool{ | |
pool: make(chan *Client, max), | |
} | |
} | |
// Borrow a Client from the pool. | |
func (p *Pool) Borrow() *Client { | |
var c *Client | |
select { | |
case c = <-p.pool: | |
default: | |
c = newClient() | |
} | |
return c | |
} | |
// Return returns a Client to the pool. | |
func (p *Pool) Return(c *Client) { | |
select { | |
case p.pool <- c: | |
default: | |
// let it go, let it go... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment