Home >Backend Development >Golang >How do you read from multiple channels simultaneously in Golang?

How do you read from multiple channels simultaneously in Golang?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 10:31:03903browse

How do you read from multiple channels simultaneously in Golang?

Reading Multiple Channels Simultaneously in Golang

As you foray into the world of Golang, you may encounter the task of creating an any-to-one channel where multiple goroutines feed into a single destination. This article will delve into strategies for achieving this in Golang.

Example Scenario

Consider a scenario where two goroutines, numgen1 and numgen2, concurrently generate numbers and write them to channels num1 and num2, respectively. Your goal is to create a separate process, addnum, that sums the numbers received from num1 and num2 and writes the results to a channel sum.

Using a Select Statement

To read from multiple channels simultaneously, you can utilize a select statement. Within the select block, each case represents a channel you want to read from. The first case that receives a message will execute its corresponding code block.

Here's an example using the select statement:

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)
}

This goroutine will run indefinitely, continuously reading and summing values from channels c1 and c2. The out channel provides a means of consuming the sums. To terminate the goroutine, you would need to close both c1 and c2 and then close out before exiting.

The above is the detailed content of How do you read from multiple channels simultaneously in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn