Skip to content

Instantly share code, notes, and snippets.

@johnny-morrice
Created February 19, 2016 09:30
Show Gist options
  • Save johnny-morrice/29385eda1e755233282b to your computer and use it in GitHub Desktop.
Save johnny-morrice/29385eda1e755233282b to your computer and use it in GitHub Desktop.
Use buffered channel to limit number of goroutines spawned
type goPool struct {
hold sync.WaitGroup
work chan func()
ready chan bool
}
func newGoPool(jobs uint) *goPool {
pool := &goPool{}
pool.ready = make(chan bool, jobs)
pool.work = make(chan func())
for i := uint(0); i < jobs; i++ {
pool.ready<- true
}
return pool
}
func (pool *goPool) run() {
go func() {
for range pool.ready {
f := <-pool.work
go func() {
f()
pool.ready<- true
}()
}
}()
}
func (pool *goPool) add(f func()) {
pool.hold.Add(1)
pool.work<- func() {
f()
pool.hold.Done()
}
}
func (pool *goPool) wait() {
pool.hold.Wait()
close(pool.work)
close(pool.ready)
}
@nightlyone
Copy link

ready should be closed by run. Only run knows when it is out of work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment