Skip to content

Instantly share code, notes, and snippets.

@reusee
Created September 25, 2012 17:25
Show Gist options
  • Save reusee/3783289 to your computer and use it in GitHub Desktop.
Save reusee/3783289 to your computer and use it in GitHub Desktop.
pool
package main
import (
"sync"
"fmt"
)
func WorkerPool(size int) chan func() {
listen := make(chan func())
pool := make(chan bool, size)
for i := 0; i < size; i++ {
pool <- true
}
go func() {
for {
fun := <-listen
go func() {
<-pool
defer func() {
pool <- true
}()
fun()
}()
}
}()
return listen
}
func main() {
workers := WorkerPool(8)
n := 500000
collect := make(map[int]bool)
wait := new(sync.WaitGroup)
for i := 0; i < n; i++ {
wait.Add(1)
argchan := make(chan int)
workers <- func() {
defer wait.Done()
arg := <-argchan
collect[arg] = true
}
argchan <- i
}
wait.Wait()
fmt.Printf("%d\n", len(collect))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment