Why is my go program getting deadlock?

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 what is going wrong ?

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()
}

and the output is:

warning: GOPATH set to GOROOT (C:\\Go) has no effect
go -  9
go -  0
go -  1
go -  2
go -  3
go -  4
go -  5
go -  6
go -  7
go -  8
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x5bcabc)
        C:/Go/src/runtime/sema.go:47 +0x2d
sync.(*WaitGroup).Wait(0x5bcab0)
        C:/Go/src/sync/waitgroup.go:127 +0xbb
main.main()
        C:/demo/go-work/main.go:20 +0xdf
exit status 2

I found the bug, I forgot that I was passing a copy of waitGroup to my function.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.