I have an example code (you can find it on Go Playground):
package main
import (
"fmt"
"sync"
"time"
)
func main() {
messages := make(chan int)
var wg sync.WaitGroup
var result []int
// you can also add these one at
// a time if you need to
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 1
}()
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 2
}()
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 3
}()
go func() {
for i := range messages {
fmt.Println(i)
result = append(result, i)
}
}()
wg.Wait()
fmt.Println(result)
}
I got this output:
2
1
[2 1]
I think I know why is it happening, but I can't solve it. There is 3 item in the WaitGroup I mean the three goroutine, and the 4th groutine consume the data from the channel. When the last groutine say wg.Done()
the program is over because of the wg.Wait() said every goroutine finished and the last goroutine result the 4th goroutine couldn't have consume, because the program ended. I tryed to add plus one with wg.Add(1) and the wg.Done() in the 4th function but in this case I got deadlock.