"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Achieve Concurrent Reading from Multiple Channels in Golang?

How Can You Achieve Concurrent Reading from Multiple Channels in Golang?

Published on 2024-11-24
Browse:120

How Can You Achieve Concurrent Reading from Multiple Channels in Golang?

Reading from Multiple Channels Concurrently in Golang

In Golang, it is possible to create an "any-to-one" channel, where multiple goroutines can write to the same channel simultaneously. Let's explore how to achieve this functionality.

One approach is to use a select statement, which allows you to wait for multiple channels to receive data:

func main() {
  // Create input channels
  c1 := make(chan int)
  c2 := make(chan int)
  // Create output channel
  out := make(chan int)

  // Start a goroutine that reads from both input channels and sums the received values
  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 runs indefinitely, reading from both channels and sending the sum of the received values to the output channel. To terminate the goroutine, it is необходимо to close both input channels.

As an alternative approach, you could use the following code:

func addnum(num1, num2, sum chan int) {
  done := make(chan bool)

  go func() {
    n1 := <-num1
    done <- true        // Signal completion of one channel read
  }()

  n2 := <-num2             // Read from the other channel
  <-done                   // Wait for the first read to complete

  sum <- n1   n2
}

This function uses a separate "done" channel to notify when one channel has been read successfully. However, this approach can be less flexible, as it requires modifying the goroutines that write to the input channels.

The appropriate approach depends on the specific requirements of your application. No matter which method you choose, Golang's concurrency features provide powerful tools for handling multiple channels simultaneously.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3