2024-01-10|閱讀時間 ‧ 約 23 分鐘

[Go]多通道監聽器

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










分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.