Skip to content

Instantly share code, notes, and snippets.

@matteo-grella
Created February 12, 2022 12:12
Show Gist options
  • Save matteo-grella/8d33aeaa64392bcb23584b24c7e30bb5 to your computer and use it in GitHub Desktop.
Save matteo-grella/8d33aeaa64392bcb23584b24c7e30bb5 to your computer and use it in GitHub Desktop.
MyPool is a naive implementation of a pool, based on broadcast channel.
package mypool
// MyPool is a naive implementation of a pool, based on broadcast channel.
// You can use this pool in the same way you use sync.Pool.
type MyPool struct {
pool chan interface{}
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
New func() interface{}
}
// NewPool returns a new pool ready to use. The pool can contain up to a max number of items.
// Set the property New to generate new items when needed during the Get.
func NewPool(max int) *MyPool {
return &MyPool{
pool: make(chan interface{}, max),
}
}
// Get selects an item from the MyPool, removes it from the MyPool, and returns it to the caller.
// If the poll is empty, Get returns the result of calling p.New.
func (p *MyPool) Get() interface{} {
var x interface{}
select {
case x = <-p.pool:
return x
default:
return p.New()
}
}
// Put adds x to the pool.
func (p *MyPool) Put(x interface{}) {
select {
case p.pool <- x:
default: // nothing to do
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment