dongpingwu8378 2014-07-18 13:30
浏览 10
已采纳

一次选择和多个案例

How to adapt the code below to do something when C1 and C2 have been BOTH received https://gobyexample.com/select

import "time"
import "fmt"

func main() {

    c1 := make(chan string)
    c2 := make(chan string)

    go func() {
        time.Sleep(time.Second * 1)
        c1 <- "one"
    }()
    go func() {
        time.Sleep(time.Second * 2)
        c2 <- "two"
    }()

    for i := 0; i < 2; i++ {
        select {
        case msg1 := <-c1:
            fmt.Println("received", msg1)
        case msg2 := <-c2:
            fmt.Println("received", msg2)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • douba1498 2014-07-18 13:36
    关注

    That could be a pipeline technique, called fan-in:

    A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that's closed when all the inputs are closed. This is called fan-in.

    func merge(cs ...<-chan int) <-chan int {
        var wg sync.WaitGroup
        out := make(chan string)
    
        // Start an output goroutine for each input channel in cs.  output
        // copies values from c to out until c is closed or it receives a value
        // from done, then output calls wg.Done.
        output := func(c <-chan string) {
            for n := range c {
                select {
                case out <- "received " + n:
                case <-done:
                }
            }
            wg.Done()
        }
        wg.Add(len(cs))
        for _, c := range cs {
            go output(c)
        }
    
        // Start a goroutine to close out once all the output goroutines are
        // done.  This must start after the wg.Add call.
        go func() {
            wg.Wait()
            close(out)
        }()
        return out
    }
    

    See a complete example in this playground


    Note: whatever solution you will end up using, a good read remains:

    Principles of designing Go APIs with channels by Alan Shreve.

    In particular:

    Principle #1

    An API should declare the directionality of its channels.

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

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?