简体   繁体   中英

Golang persistent channel accepting input from multiple function calls

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 .

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\n", 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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM