Created
May 9, 2019 03:28
-
-
Save lkebin/b618b4f9c3bccb05bde777a2e59c12fe to your computer and use it in GitHub Desktop.
Golang sync.WaitGroup example https://play.golang.org/p/NIRRu05m4Ub
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" | |
"sync" | |
) | |
func main() { | |
var workers = 4 | |
var wg sync.WaitGroup | |
var chains = make([]chan int, workers) | |
for i := 0; i < workers; i++ { | |
chains[i] = make(chan int) | |
wg.Add(1) | |
go func(c chan int) { | |
defer wg.Done() | |
for { | |
n, more := <-c | |
if more { | |
fmt.Println(n) | |
} else { | |
fmt.Println("close") | |
return | |
} | |
} | |
}(chains[i]) | |
} | |
for i := 0; i < 1000; i++ { | |
chains[i%workers] <- i | |
} | |
for i := 0; i < workers; i++ { | |
close(chains[i]) | |
} | |
wg.Wait() | |
fmt.Println("Hello, playground") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment