关于Go通道教程中一些缺失的单词或词组的澄清

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

Clarification on Go channels tutorial from some missing word or words

问题

这个关于 Go 通道的教程页面似乎缺少一个词或者没有编辑好。我无法确定它应该如何描述通过通道发送和接收的内容。

默认情况下,发送和接收会阻塞,直到另一侧准备好。

在 Go 中,block 是什么意思?我以前没见过这个词。这里的 block 是作为名词使用吗?

我试着搜索了一下以澄清这个问题。唯一另一个有类似措辞的页面是 educative.io

此外,默认情况下,通道会发送和接收,直到另一侧准备好。

但这没有意义。他们是不是指:

  • 无论另一侧是否准备好,通道都会发送和接收?这不是很浪费吗?

  • 或者上述陈述中是否缺少了“”?

英文:

This page on a Go Tutorial about channels seems to be missing a word(s) or was just not edited. I can't tell what it is supposed to say about sending and receiving through channels.

> By default, sends and receives block until the other side is ready.

Is a block something within Go? I haven't seen it before. Is block being used as a noun?

I tried searching for clarification. The only other page that has similar wording is educative.io

> Moreover, by default, channels send and receive until the other side is ready

But it doesn't make sense. Do they mean:

  • Channels send and receive regardless of whether or not the other side is ready? Doesn't this seem wasteful?

  • Or is "don't" missing in the statement above?

答案1

得分: 2

"Block"的意思是goroutine将会等待。你可以这样写:

默认情况下,发送和接收操作会等待对方准备好。

"Block"只是这种情况的常用术语,并不特定于Go语言。在Go语言中,可以以非阻塞的方式使用通道:

  1. 可以创建一个带有缓冲区的通道。只要缓冲区中有空间,写操作就是非阻塞的(但如果缓冲区已满,则会阻塞)。只要缓冲区中有数据,读操作就是非阻塞的(但如果缓冲区为空,则会阻塞)。

  2. 可以使用带有default分支的select语句。

var readch chan int
var writech chan int
var value int
select {
case n := <- readch:
    // 接收到数据。
case writech <- value:
    // 发送数据。
default:
    // 没有发送或接收数据。
}

在这段代码中,goroutine不会阻塞(等待),而是会执行default分支。

英文:

"Block" means that the goroutine will wait. You could write it this way:

> By default, sends and receives wait until the other side is ready.

"Block" is just the normal term for this. It is not specific to Go. It is possible to use a channel in Go in a non-blocking manner:

  1. You can create a channel with a buffer. As long as there is space in the buffer, a write is non-blocking (but it will block if the buffer is full). As long as there is data in the buffer, a read is non-blocking (but it will block if the buffer is empty).

  2. You can use a select statement with a default branch.

var readch chan int
var writech chan int
var value int
select {
case n := &lt;- readch:
    // Received data.
case writech &lt;- value:
    // Sent data.
default:
    // Didn&#39;t send or receive data.
}

In this code, instead of blocking (waiting), the goroutine will go to the default branch.

huangapple
  • 本文由 发表于 2022年9月5日 02:07:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73601720.html
匿名

发表评论

匿名网友

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

确定