asynchronous - Golang persistent channel accepting input from multiple function calls -


i have function a:

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

this function gets called multiple times. want function b wait indefinitely input function a , perform action when has collected n inputs.

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

how go doing this? first thought use sync.waitgroup channel between a , b.

this common producer-consumer problem. use channels wait on input routine. help?

in particular example, have call go b(c) again after collecting inputs terminates, wrap whatever b in infinite for loop. or whatever needs happen.

please note in example, , unbuffered channel used, forces both routines meet @ same time "hand off" *thing. if want producer (a's process) not have wait, can use buffered channel, created so:

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

where n number of items channel can store. allows several queued 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{}     := 0; < 10; i++ {         t := <-c         things = append(things, t)         fmt.printf("i have %d things\n", i+1)     }     fmt.println("i have 10 things! let's roll!")     // stuff ten things }  func main() {     fmt.println("hello, playground")     c := make(chan (*thing))      go b(c)      // done producer-consumer in go-routine     := 0; < 10; i++ {         a(&thing{i}, c)         time.sleep(time.second)     }     time.sleep(time.second)     fmt.println("program finished") } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -