Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://stackoverflow.com/questions/70876451/channels-and-wait-groups-entering-deadlock
- func main() {
- channel := make(chan string)
- var wg sync.WaitGroup
- for i := 0; i < 10; i++ {
- wg.Add(1)
- go performTest(channel, &wg, i)
- }
- // this is the trick
- go func() {
- wg.Wait()
- close(channel)
- }()
- for line := range channel {
- fmt.Print(line)
- }
- }
- func performTest(channel chan string, wg *sync.WaitGroup, i int) {
- defer wg.Done()
- // perform some work here
- result := fmt.Sprintf("Pretend result %d\n", i)
- channel <- result
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement