Created
September 25, 2012 17:25
-
-
Save reusee/3783289 to your computer and use it in GitHub Desktop.
pool
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
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