douju2599 2013-05-19 19:32
浏览 44
已采纳

为什么这个Google I / O 2012并发示例无法正常工作?

I'm trying to follow along with Rob Pike's Google I/O 2012 talk called "Go Concurrency". I'm trying the example where channels are multiplexed so "Ann" and "Joe" don't talk in lock-step. But using the code below, they still are lock-stepping. Where am I going wrong?

Video: http://www.youtube.com/watch?v=f6kdp27TYZs&feature=player_detailpage#t=1025s

package main

import (
    "fmt"
    "time"
    "math/rand"
    )

func fanIn(input1, input2 <-chan string) <-chan string {
    c := make(chan string)
    go func() { for {c <- <-input1 } }()
    go func() { for {c <- <-input2 } }()
    return c
}

func main() {
    c := fanIn(boring("Joe"), boring("Ann"))
    for i:=0; i<10; i++ {
        fmt.Println(<-c)
    }
    fmt.Printf("You're both boring, I'm leaving...
")
}

func boring(msg string) <-chan string {
    c := make(chan string)
    go func() { // launch goroutine from inside the fn
        for i:=0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond )
        }
    }()
    return c
}

And the output of this (go version go1.0.2 on Ubuntu 10.04 LTS)

Joe 0
Ann 0
Joe 1
Ann 1
Joe 2
Ann 2
Joe 3
Ann 3
Joe 4
Ann 4
You're both boring, I'm leaving...

Where did I go wrong? Thanks!

  • 写回答

1条回答 默认 最新

  • du7979 2013-05-19 19:52
    关注

    Your code is fine; it just tends to take a little more than that to get them out of sync. Just loop more times and you should see them get out of lock-step:

    for i := 0; i < 20; i++ { // Going up to 20 is enough to usually see it
        fmt.Println(<-c)
    }
    

    I got this output:

    Joe 0
    Ann 0
    Joe 1
    Ann 1
    Joe 2
    Ann 2
    Joe 3
    Ann 3
    Joe 4
    Ann 4
    Joe 5
    Ann 5
    Joe 6
    Ann 6
    Ann 7
    Joe 7
    Joe 8
    Joe 9
    Ann 8
    Ann 9
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?