Created
February 19, 2016 09:30
-
-
Save johnny-morrice/29385eda1e755233282b to your computer and use it in GitHub Desktop.
Use buffered channel to limit number of goroutines spawned
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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ready should be closed by run. Only run knows when it is out of work.