Go 通道中发送者的顺序

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

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 (
    &quot;fmt&quot;
    &quot;time&quot;
)

func pinger(c chan string) {
    for i := 0; ; i++ {
        c &lt;- &quot;ping&quot;
    }
}

func ponger(c chan string) {
    for i := 0; ; i++ {
        c &lt;- &quot;pong&quot;
    }
}

func printer(c chan string) {
    for {
        msg := &lt;- 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(&amp;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

pingpong 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.

huangapple
  • 本文由 发表于 2015年3月17日 05:46:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/29087538.html
匿名

发表评论

匿名网友

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

确定