Last active
April 1, 2019 10:20
-
-
Save tkrs/7ba5ddbc4c85c6e66711 to your computer and use it in GitHub Desktop.
Example golang of channels and syn.WaitGroup
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 ( | |
"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