Home > OS >  Channel causes panic when called on same scope
Channel causes panic when called on same scope

Time:01-07

Can someone explain to me why the first code runs but the second one fails?

First One :

func main() {

  channel := make(chan int)
  go demo(channel)
  num := <-channel
  println(num)

}

func demo(channel chan int) {
  channel <- 2
}

Second One:

func main() {
    demo()
}

func demo() {
    channel := make(chan int)
    channel <- 2
    num := <-channel
    println(num)
}

In the second one, I am taking the input from the channel in the demo function but it still creates a deadlock can someone explain this in brief. What I can see is when I am calling the channel in the same scope it's causing an issue.

CodePudding user response:

Your channel is unbuffered so writing to it will block since no other goroutines can read from it.

Make this change and it will run:

channel := make(chan int, 1)

CodePudding user response:

In the first case, write to channel is in a separate goroutine. When the main goroutine blocks reading from the channel, there is still one goroutine that can write to the channel, thus is it not a deadlock. Eventually that goroutine writes to the channel and the program completes.

In the second case, write to channel blocks, and there are no other goroutines running, so it is a deadlock.

  •  Tags:  
  • Related