Skip to content

Instantly share code, notes, and snippets.

@glesica
Created May 20, 2015 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glesica/2c4ddcc5c9e71cba442b to your computer and use it in GitHub Desktop.
Save glesica/2c4ddcc5c9e71cba442b to your computer and use it in GitHub Desktop.
Dynamic pool that allows concurrency for a set of tasks to be throttled.
package main
import "sync"
func main() {
jobChan := make(chan (chan int))
resChan := make(chan int)
squareGroup := new(sync.WaitGroup)
// The workers
for i := 0; i < 5; i++ {
squareGroup.Add(1)
go func() {
for taskChan := range jobChan {
for n := range taskChan {
resChan <- n * n
}
}
squareGroup.Done()
}()
}
// The "submitter"
go func() {
taskChan := make(chan int)
for i := 0; i < 1; i++ {
jobChan <- taskChan
}
for i := 0; i < 10; i++ {
taskChan <- i
}
close(taskChan)
close(jobChan)
squareGroup.Wait()
close(resChan)
}()
// Collect the results back in the main goroutine
for s := range resChan {
println(s)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment