I am trying to understand synchronisation in Goroutines. I have a code here that writes numbers from 0 to 4 on a channel and once done I read from the channel using range and print the values.
The below code works fine where I am waiting using wg.Wait() and closing the channel in a separate Goroutine.
package main
import "fmt"
import "strconv"
import "sync"
func putvalue(i chan string, value string, wg *sync.WaitGroup) {
i <- value
defer wg.Done()
}
func main() {
queue := make(chan string)
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go putvalue(queue, strconv.Itoa(i), &wg)
}
go func() {
wg.Wait()
close(queue)
}()
for elem := range queue {
fmt.Println(elem)
}
}
But if I use the exact same code, but wait and close the channel in the main thread, this results in a deadlock. The below code results in deadlock.
package main
import "fmt"
import "strconv"
import "sync"
func putvalue(i chan string, value string, wg *sync.WaitGroup) {
i <- value
defer wg.Done()
}
func main() {
queue := make(chan string)
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go putvalue(queue, strconv.Itoa(i), &wg)
}
wg.Wait()
close(queue)
for elem := range queue {
fmt.Println(elem)
}
}
From what I can understand that in the second case the main thread execution stops and waits, but how is it different from doing it in a separate goroutine? Please help me understand this.