这个”检查通道是否关闭”的工作原理是怎样的?

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

How is this "checking if a channel is closed" working?

问题

var msg = make(chan string)

func checkChannelAndSendMessage() {
select {
case <-msg:
fmt.Print("channel is closed")
default:
msg <- "hey"
}
}

func readMessage() {
for {
fmt.Print(<-msg)
}
}

我有一段代码触发了checkChannelAndSendMessage函数。我不明白这个select语句是如何工作的,它是如何检查通道是否打开,并且只在通道打开时发送消息的。有人可以解释一下吗?

英文:
var msg = make(chan string)


func checkChannelAndSendMessage() {
    select {
    	case &lt;-msg:
    		fmt.Print(&quot;channel is closed&quot;)
    	default:
    		msg &lt;- &quot;hey&quot;
    	}
}

func readMessage() {
  for {
    fmt.Print(&lt;-msg)
  }
}

I have a piece of code which triggers checkChannelAndSendMessage function. I don't understand how this select statement is working to check if a channel is open and then sending messages only if channel is open. Someone please explain it.

答案1

得分: 1

default:情况将在通道打开且没有其他goroutine向该通道发送数据时执行。case <-msg:情况将在通道关闭(返回通道元素类型的零值)时执行,或者在其他goroutine向该通道发送数据时执行。

这意味着该函数本身并不是绝对可靠的,它可能会在通道实际上是打开的情况下打印"channel is closed"

英文:

The default: case will be executed if the channel is open and no other goroutine is sending data to that channel. The case &lt;-msg: case will be executed if the channel is closed (returning the zero value of the channel's element type), or it will be executed if some other goroutine is sending data to that channel.

That means that the function by itself is not foolproof, it could very well be used in such a way that it'd print &quot;channel is closed&quot; even while the channel is actually open.

huangapple
  • 本文由 发表于 2022年7月27日 14:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73132919.html
匿名

发表评论

匿名网友

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

确定