Here is my Golang program which I am playing with just to get my concepts right. When I run the program it is deadlocked I don\'t understand why ? Please anyone point out wh
The problem is that you're passing a copy of sync.WaitGroup
to the goroutines, rather than a reference (i.e. a pointer):
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
numOfGoRoutines := 10
wg.Add(numOfGoRoutines)
ch := make(chan int, numOfGoRoutines)
for i := 0; i < numOfGoRoutines; i++ {
a := i
go sqr(ch, a, &wg)
}
wg.Wait()
fmt.Println("After WAIT")
close(ch)
var res int
for i := range ch {
res += i
}
ch = nil
fmt.Println("result = ", res)
}
func sqr(ch chan int, val int, wg *sync.WaitGroup) {
fmt.Println("go - ", val)
s := val * val
ch <- s
wg.Done()
}
Additionally, since wg
is a global variable, you could just remove the parameter entirely:
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
numOfGoRoutines := 10
wg.Add(numOfGoRoutines)
ch := make(chan int, numOfGoRoutines)
for i := 0; i < numOfGoRoutines; i++ {
a := i
go sqr(ch, a)
}
wg.Wait()
fmt.Println("After WAIT")
close(ch)
var res int
for i := range ch {
res += i
}
ch = nil
fmt.Println("result = ", res)
}
func sqr(ch chan int, val int) {
fmt.Println("go - ", val)
s := val * val
ch <- s
wg.Done()
}