dongzhan5246 2017-04-07 16:48
浏览 102
已采纳

Golang持久通道接受来自多个函数调用的输入

I have a function a:

func a(input *some_type) {
    // do sth.
    b(input)
    }

This function gets called multiple times. I want a function b to wait indefinitely for input from function a and perform an action when it has collected n inputs.

func b(input *some_type) {
    // wait until received n inputs then do sth. with all inputs
    }

How would I go about doing this? My first thought was to use a sync.WaitGroup with a channel between a and b.

  • 写回答

1条回答 默认 最新

  • douji6461 2017-04-07 17:01
    关注

    This is a common producer-consumer problem. Use channels to wait on the input from another routine. Does something like this help?

    In this particular example, you would have to call go b(c) again after collecting the inputs as it terminates, but you could easily wrap whatever b does in an infinite for loop. Or whatever needs to happen.

    Please note that in this example, and unbuffered channel is used, which forces both routines to meet at the same time to "hand off" the *Thing. If you want the producer (a's process) to not have to wait, you can use a buffered channel, which is created like so:

    c := make(chan(*Thing, n))
    

    Where n is the number of items the channel can store. This allows several to be queued by the producer.

    https://play.golang.org/p/X14_QsSSU4

    package main
    
    import (
        "fmt"
        "time"
    )
    
    type Thing struct {
        N int
    }
    
    func a(t *Thing, c chan (*Thing)) {
        // stuff happens. whee
        c <- t
    }
    
    func b(c chan (*Thing)) {
        things := []*Thing{}
        for i := 0; i < 10; i++ {
            t := <-c
            things = append(things, t)
            fmt.Printf("I have %d things
    ", i+1)
        }
        fmt.Println("I now have 10 things! Let's roll!")
        // do stuff with your ten things
    }
    
    func main() {
        fmt.Println("Hello, playground")
        c := make(chan (*Thing))
    
        go b(c)
    
        // this would probably be done producer-consumer like in a go-routine
        for i := 0; i < 10; i++ {
            a(&Thing{i}, c)
            time.Sleep(time.Second)
        }
        time.Sleep(time.Second)
        fmt.Println("Program finished")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作