It dead locks because both the calc()
and the main()
function reads from the channel before anyone gets to write to it.
So you will end up having every (non-main) go routine blocking at:
ans := <-*c
waiting for someone other go routine to enter a value into the channel. There fore none of them gets to the next line where they actually write to the channel. And the main()
routine will block at:
ans := <-c
Everyone is waiting = deadlock
Using buffered channels
Your solution should have the calc()
function only writing to the channel, while the main()
could read from it in a for-range
loop, suming up the values coming from the go-routines.
You will also need to add a way for main()
to know when there will be no more values arriving, perhaps by using a sync.WaitGroup
(maybe not the best, since main
isn't suppose to wait but rather sum things up) or an ordinary counter.
Using shared memory
Sometimes it is not necessarily a channel you need. Having a shared value that you update with the (atomic add doesn't work on floats) lock with a sync/atomic
packagesync.Mutex
works fine too.