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 怎么改成输入一个要删除的数后现实剩余的数再输入一个删除的数再现实剩余的数用yes表示继续no结束程序
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?