dousi5358 2015-03-16 21:46
浏览 29
已采纳

Go频道中的发件人顺序

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?

  • 写回答

2条回答 默认 最新

  • dongshan9619 2015-03-16 22:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效