[Go]多通道監聽器

小黑
發佈於後端
2024/01/10閱讀時間約 2 分鐘
package main

import (
"fmt"
)

func foo(i int) chan int {
ch := make(chan int)
go func() { ch <- i }()
return ch
}

func main() {
ch1, ch2, ch3 := foo(3), foo(6), foo(9)

ch := make(chan int)

//開一個goroutine監視各個通道資料輸出並收集資料到通道ch
go func() {
for {
//timeout是一個計時通道, 如果達到時間了,就會發出一個訊號出來
timeout := time.After(1 * time.Second)
for isTimeout := false; !isTimeout; {
//監視通道ch1, ch2, ch3, timeout通道的資料流出
select { //監視通道ch1, ch2, ch3, timeout通道的資料流出
case v1 := <-ch1:
fmt.Printf("received %d from ch1", v1)
case v2 := <-ch2:
fmt.Printf("received %d from ch2", v2)
case v3 := <-ch3:
fmt.Printf("received %d from ch3", v3)
case <-timeout:
isTimeout = true //超時
}
}
}
}()

//阻塞主線,取出通道ch的數據
for i := 0; i < 3; i++ {
fmt.Println(<-ch)
}
}










7會員
78內容數
嗨,我是一名程式設計師,會在這分享開發與學習紀錄。
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容