Skip to content

Instantly share code, notes, and snippets.

@tkrs
Last active April 1, 2019 10:20
Show Gist options
  • Save tkrs/7ba5ddbc4c85c6e66711 to your computer and use it in GitHub Desktop.
Save tkrs/7ba5ddbc4c85c6e66711 to your computer and use it in GitHub Desktop.
Example golang of channels and syn.WaitGroup
package main
import (
"fmt"
"runtime"
"sync"
)
func init() {
fmt.Println("func init()")
}
func sq(out chan int) {
defer close(out)
x := cap(out)
for i := 0; i < x; i++ {
out <- i * i
}
}
func worker(n int) {
_ = n * n * n
}
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func main() {
const N = 100000
ch := make(chan int, N)
go sq(ch)
for _ = range ch {
}
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
worker(i)
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment