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"
"strconv"
"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)
}
}
https://play.golang.org/p/OtaRP3Mm4lk
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"
"strconv"
"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)
}
}
https://play.golang.org/p/JXmdsdPKQPu
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.