Created
August 9, 2012 10:07
-
-
Save apg/3302915 to your computer and use it in GitHub Desktop.
untested (but probably functional) Go pool
This file contains hidden or 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
package pool | |
import ( | |
"container/list" | |
"sync" | |
) | |
type Pool struct { | |
capacity int | |
cons func() interface{} | |
ready *list.List | |
lock *sync.Mutex | |
} | |
func New(capacity int, cons func() interface{}) *Pool { | |
ret = new(Pool) | |
ret.capacity = capacity | |
ret.cons = cons | |
ret.ready = list.New() | |
ret.ready.Init() | |
ret.lock = new(sync.Mutex) | |
return ret | |
} | |
func (p *Pool) Get() interface{} { | |
p.lock.Lock() | |
e := ready.Front() | |
if e != nil { | |
ready.Remove(e) | |
p.lock.Unlock() | |
return e.Value | |
} | |
p.lock.Unlock() | |
// else create a new one and return that | |
ret := p.cons() | |
return n | |
} | |
func (p *Pool) Put(thing interface{}) { | |
p.lock.Lock() | |
if p.ready.Len() < p.capacity { | |
p.ready.PushFront(thing) | |
} | |
p.lock.Unlock() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment