英文:
Ordering of senders in a Go channel
问题
考虑一下来自http://www.golang-book.com/10/index.htm#section2的乒乓球示例。
package main
import (
"fmt"
"time"
)
func pinger(c chan string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c chan string) {
for {
msg := <- c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}
func main() {
var c chan string = make(chan string)
go pinger(c)
go ponger(c)
go printer(c)
var input string
fmt.Scanln(&input)
}
作者写道:
"程序现在将轮流打印ping和pong。"
然而,为了实现这一点,Go必须决定发送者可以按照什么顺序向通道发送数据。否则,无法保证在发送pong之前会发送ping(即无法连续获得两个ping或两个pong)。这是如何工作的呢?
英文:
Consider the ping pong example from http://www.golang-book.com/10/index.htm#section2.
package main
import (
"fmt"
"time"
)
func pinger(c chan string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c chan string) {
for {
msg := <- c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}
func main() {
var c chan string = make(chan string)
go pinger(c)
go ponger(c)
go printer(c)
var input string
fmt.Scanln(&input)
}
The authors write:
> "The program will now take turns printing ping and pong."
However, for this to be true, Go must decide on an order in which senders can send into a channel? Otherwise, there would be no guarantee that a ping would be sent before a pong (i.e. you can't get two pings, or two pongs in a row). How does this work?
答案1
得分: 7
ping
和pong
goroutine之间没有同步,因此不能保证响应按顺序打印。
如果你强制让goroutine在GOMAXPROCS>1的情况下竞争,输出将是随机的:
pong
ping
ping
pong
ping
pong
ping
pong
pong
这甚至不是一个“乒乓球”示例,因为没有调用和响应。
英文:
There is no synchronization between the ping
and pong
goroutines, therefore there is no guarantee that the responses will print in order.
If you force the goroutines to race with GOMAXPROCS>1, you get random output:
pong
ping
ping
pong
ping
pong
ping
pong
pong
This isn't even an example of a "ping-pong", since there's is no call and response.
答案2
得分: 1
最近有一个关于消息进入通道的选择顺序的相关问题。
答案是选择顺序通常是非确定性的。这是有意为之的。
英文:
There was a related question on the order of selection of messages entering a channel recently.
The answer is that the order is normally non-deterministic. This is intentional.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论