Golang 中同時讀取多個通道
在Golang 中,可以建立一個「任意對一」的通道,其中多個goroutine 可以同時寫入同一個頻道。讓我們探討一下如何實現這個功能。
一種方法是使用 select 語句,它允許您等待多個通道接收資料:
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)
}
這個 goroutine 無限期地運行,從兩個通道讀取並將接收到的值的總和發送到輸出通道。要終止 goroutine,需要關閉兩個輸入通道。
作為替代方法,您可以使用以下程式碼:
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
}
此函數使用單獨的「完成」通道來通知何時成功讀取一個通道。然而,這種方法可能不太靈活,因為它需要修改寫入輸入通道的 goroutine。
適當的方法取決於應用程式的特定要求。無論您選擇哪種方法,Golang 的並發特性都提供了同時處理多個通道的強大工具。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3