godeadlockchannelgoroutinewaitgroup

Issue in invoking go routine & passing data to channel fatal error: all goroutines are asleep - deadlock


I am trying to increment a value using go function & invoke the function as goroutine, but i am getting error.

Here is the Code:

package main

import (
    "fmt"

)

func incNum(ch chan int) {

    val := <-ch
    ch <- val + 10

}

func main() {

    ch := make(chan int)

    ch <- 10

    go incNum(ch)

    fmt.Println("Result", ch)

}

I tried adding the wait also but doesn't work:

ch := make(chan int)

wg.Add(1) // 2
ch <- 10

go incNum(ch)

wg.Wait() // 4

fmt.Println("Result", ch)

Below is the error:

fatal error: all goroutines are asleep - deadlock!

Please Help!


Solution

  • In your code snippet, main goroutine blocking in putting value in zero buffered channel:

    func incNum(ch chan int) {
        val := <-ch // release value
        ch <- val + 10
    
    }
    
    func TestName(t *testing.T) {
    
        ch := make(chan int) // zero buffered channel
    
        ch <- 10 // main goroutine is blocked while ch will released value (on zero buffered chan)
    
        go incNum(ch)
    
        //fmt.Println("Result", ch)
        fmt.Println("Result", <-ch)
    }
    

    move go incNum(ch) before ch <- 10

    func TestName(t *testing.T) {
    
        ch := make(chan int) // zero buffered channel
    
        go incNum(ch)
    
        ch <- 10
    
        //fmt.Println("Result", ch)
        fmt.Println("Result", <-ch)
    }