Reading from multiple channels simultaneously in the Golang

I am new to Golang. Now I'm trying to figure out how to make a one-to-one channel in the Golang, where the setup looks like this:

Let's say I have two gotoutines numgen1 and numgen2 running at the same time and writing numbers to the num1 resp channels. num2. I would like to add numbers sent from numgen1 and numgen2 to a new process, addnum. I tried something like this:

func addnum(num1, num2, sum chan int) { done := make(chan bool) go func() { n1 := <- num1 done <- true }() n2 := <- num2 <- done sum <- n1 + n2 } 

but this is sadly wrong. Can someone please give me some ideas?

Many thanks for your help.

+8
concurrency go channels
source share
3 answers

Depending on your requirements, you may need to read both channels for each iteration (ie, a function like "zip"). You can do this with select, similar to user860302 :

 func main() { c1 := make(chan int) c2 := make(chan int) out := make(chan int) go func(in1, in2 <-chan int, out chan<- int) { for { sum := 0 select { case sum = <-in1: sum += <-in2 case sum = <-in2: sum += <-in1 } out <- sum } }(c1, c2, out) } 

It works forever. My preferred way to finish mountains like this is to close the input channels. In this case, you will need to wait until both are closed, and then close(out) until completion.

Tip. Pay attention to the use of directional channels as formal parameters of goroutin. The compiler catches more errors when you write it like this. Happiness!

+7
source share

The simplest answer is

 func addnum(num1, num2, sum chan int) { n1 := <- num1 n2 := <- num2 sum <- n1 + n2 } 

Since you need both num1 and num2 to perform the calculations, it makes no sense to do it differently. In the end, there are two possible implementations:

  • num1 generates a number followed by num2
  • num2 generates a number followed by num1

In the first case, our channel corresponds exactly to the performance. In the second case, our first reading will be blocked until num1 finally num1 number; the second reading will be completed almost instantly, because channel num2 already has a number.

If you want to know more about channels in Go, I would suggest looking at http://godoc.org/github.com/thomas11/csp - this is a collection of Hoare CSP examples written in Go.

+4
source share

To answer the question "Reading from multiple feeds at once"

There is a way to listen to multiple channels simultaneously:

 func main() { c1 := make(chan string) c2 := make(chan string) ... go func() { for { select { case msg1 := <- c1: fmt.Println(msg1) case msg2 := <- c2: fmt.Println(msg2) } } }() 

In this example, I create the msg1 and msg2 channels. Then I create a routine with an infinite loop. In this loop, I listen to msg1 and msg2. This system allows you to simultaneously view multiple channels and process messages when they arrive.

To avoid leaks, I probably should add another channel to stop goroutine.

+2
source share

All Articles