英文:
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语言中,可以以非阻塞的方式使用通道:
-
可以创建一个带有缓冲区的通道。只要缓冲区中有空间,写操作就是非阻塞的(但如果缓冲区已满,则会阻塞)。只要缓冲区中有数据,读操作就是非阻塞的(但如果缓冲区为空,则会阻塞)。
-
可以使用带有
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:
-
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).
-
You can use a
select
statement with adefault
branch.
var readch chan int
var writech chan int
var value int
select {
case n := <- readch:
// Received data.
case writech <- value:
// Sent data.
default:
// Didn't send or receive data.
}
In this code, instead of blocking (waiting), the goroutine will go to the default
branch.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论