Search code examples
godeadlockgoroutine

Dead lock in goroutines


can someone give me some insight about this code, Why this get deadlock error in for x:=range c

func main() {
    c:=make(chan int,10)

    for i:=0;i<5;i++{
        go func(chanel chan int,i int){
            println("i",i)
            chanel <- 1
        }(c,i)
    }

    for x:=range c {
        println(x)
    }
    println("Done!")
}

Solution

  • Because this:

        for x:=range c {
            println(x)
        }
    

    will loop until the channel c closes, which is never done here.

    Here is one way you can fix it, using a WaitGroup:

    package main
    
    import "sync"
    
    func main() {
        var wg sync.WaitGroup
        c := make(chan int, 10)
    
        for i := 0; i < 5; i++ {
            wg.Add(1)
            go func(chanel chan int, i int) {
                defer wg.Done()
                println("i", i)
                chanel <- 1
            }(c, i)
        }
    
        go func() {
            wg.Wait()
            close(c)
        }()
    
        for x := range c {
            println(x)
        }
        println("Done!")
    }
    

    Try it on Go Playground