当在相同的作用域上调用`Channel`时会引发恐慌。

huangapple go评论83阅读模式
英文:

Channel causes panic when called on same scope

问题

第一个代码运行成功而第二个代码失败的原因是什么?第二个代码中,我在demo函数中从通道中接收输入,但仍然导致了死锁。有人能简要解释一下吗?我所看到的是,当我在同一作用域中调用通道时,会出现问题。

英文:

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.

答案1

得分: 5

你的通道是无缓冲的,因此写入它将会阻塞,因为没有其他goroutine可以从中读取。

进行以下更改,它将会运行:

channel := make(chan int, 1)
英文:

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)

答案2

得分: 3

在第一种情况下,写入通道的操作在一个单独的 goroutine 中进行。当主 goroutine 阻塞在通道读取时,仍然有一个 goroutine 可以写入通道,因此不会发生死锁。最终,该 goroutine 会写入通道,程序完成。

在第二种情况下,写入通道被阻塞,并且没有其他正在运行的 goroutine,因此会发生死锁。

英文:

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.

huangapple
  • 本文由 发表于 2022年1月7日 02:31:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/70611913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定