Advertisement
andrejsstepanovs

golang wait group channel

Oct 24th, 2023
830
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.62 KB | None | 0 0
  1. // https://stackoverflow.com/questions/70876451/channels-and-wait-groups-entering-deadlock
  2. func main() {
  3.     channel := make(chan string)
  4.     var wg sync.WaitGroup
  5.     for i := 0; i < 10; i++ {
  6.         wg.Add(1)
  7.         go performTest(channel, &wg, i)
  8.     }
  9.    
  10.     // this is the trick
  11.     go func() {
  12.         wg.Wait()
  13.         close(channel)
  14.     }()
  15.  
  16.     for line := range channel {
  17.         fmt.Print(line)
  18.     }
  19. }
  20.  
  21. func performTest(channel chan string, wg *sync.WaitGroup, i int) {
  22.     defer wg.Done()
  23.     // perform some work here
  24.     result := fmt.Sprintf("Pretend result %d\n", i)
  25.     channel <- result
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement