Reputation: 38180
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)
}
}
}
Upvotes: 7
Views: 11863
Reputation: 1323433
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:
An API should declare the directionality of its channels.
Upvotes: 7