Hi,

you need to spin up another goroutine which ranges over the channel:
https://play.golang.org/p/OhLd6vOBYE

The reason for the deadlock is: You spin up N workers which are sending
the results over the "fact_chan"-Channel. After you did this, you are
listening on the main-routine for messages on fact_chan forever. But
after all of the workers finished their tasks, there is nobody to send
data. The runtime detects this and panics.

- Jannick

Am 04.08.2017 um 17:11 schrieb prankpla...@gmail.com:
> *Factorial Program in GoLang. Encountering deadlock.*
> *
> *
> *Hello All,*
> *
> *
> I am pretty new to GoLang , so please excuse me if question/doubt is silly. 
> 
> I am trying to write a Factorial program of numbers ranging from 0 to 5.
> My goal is to launch separate GO routines for each number and then
> collect o/p and print it. I have tries writing code which can be seen
> @ https://play.golang.org/p/MTzTuroxE5 (also below) .. but i am
> encountering DEADLOCK error. I have been trying to synchronize it but i
> have failed to do it so far. Please help me in understanding that how
> else i can write this program so that i properly close sending channel
> to avoid error.
> 
> --
> package main
> 
> import (
> "fmt"
> "sync"
> )
> 
> var wg sync.WaitGroup
> 
> func factorial(x int) int {
> if x > 0 {
> return x*factorial(x-1)
> }
> return 1
> }
> 
> func fact_worker(fact_resp_chan chan string, x int) {
> defer wg.Done()
> response := factorial(x)
> fact_resp_chan <-  fmt.Sprintf("Factorial of %d is : %d", x, response)
> }
> 
> 
> func main() {
> fact_chan := make(chan string)
> 
> for n := 0; n <=5 ; n++ {
> wg.Add(1)
> go fact_worker(fact_chan, n)
> }
> 
> 
> 
> for resp := range(fact_chan) {
> fmt.Printf("%s\n", resp)
> }
> wg.Wait()
> 
> }
> --
> 
> Thanks!
> 
> -- 
> You received this message because you are subscribed to the Google
> Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to golang-nuts+unsubscr...@googlegroups.com
> <mailto:golang-nuts+unsubscr...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to