dqzuo0327 2014-08-20 12:03
浏览 35
已采纳

使用fanIn功能多路复用Go常规输出

I was trying to implement an example Go code for using returned channels from go routines without any "reading block" in the main function. Here, a fanIn function accepts channels from two other routines and return which got as input.

Here, the expected output is Random Outputs from two inner routines. But the actual output is always one "ann" followed by a "john", not at all random in any case.

Why am I not getting random output?

Go Playground: http://play.golang.org/p/46CiihtPwD

Actual output:

  you say: ann,0 
  you say: john,0
  you say: ann,1
  you say: john,1 
   ......

Code:

package main

import (
    "fmt"
    "time"
)

func main() {

    final := fanIn(boring("ann"), boring("john"))

    for i := 0; i < 100; i++ {
        fmt.Println("you say:", <-final)

    }
    time.Sleep(4 * time.Second)
}

func boring(msg string) chan string {
    c1 := make(chan string)
    go func() {
        for i := 0; ; i++ {
            c1 <- fmt.Sprintf("%s,%d", msg, i)
            time.Sleep(time.Second)

        }
    }()
    return c1
}

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

1条回答 默认 最新

  • duanfan1965 2014-08-20 13:11
    关注

    No particular reason, that's just how Go happens to schedule the relevant goroutines (basically, you're getting "lucky" that there's a pattern). You can't rely on it. If you really want an actual reliably random result, you'll have to manually mix in randomness somehow.

    There's also the Multiplex function from https://github.com/eapache/channels/ (doc: https://godoc.org/github.com/eapache/channels#Multiplex) which does effectively the same thing as your fanIn function. I don't think it would behave any differently in terms of randomness though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64