golang如何收听N个频道?
在Go语言中,可以使用select
语句来同时收听多个频道。下面是一个示例代码,演示如何收听N个频道并处理它们的消息:
package main import ( "fmt" "time" ) func main() { channel1 := make(chan string) channel2 := make(chan string) go emit(channel1, "Channel 1") go emit(channel2, "Channel 2") // 使用 select 语句收听多个频道 for i := 0; i < 10; i++ { select { case msg := <-channel1: fmt.Println("Received from Channel 1:", msg) case msg := <-channel2: fmt.Println("Received from Channel 2:", msg) case <-time.After(1 * time.Second): fmt.Println("Timeout! No message received.") } } } // 发送消息到频道 func emit(ch chan<- string, msg string) { for i := 0; ; i++ { ch <- fmt.Sprintf("%s: %d", msg, i) time.Sleep(500 * time.Millisecond) } }
在上面的代码中,我们创建了两个频道channel1
和channel2
,然后使用go
关键字启动两个goroutine来发送消息到这两个频道。在主goroutine中的select
语句中,我们可以同时收听这两个频道,并根据收到的消息进行相应的处理。
在每次循环中,select
语句会尝试从所有的频道中接收消息。如果某个频道有可用的消息,就会执行对应的case
分支。如果所有的频道都没有消息可用,那么select
语句会执行default
分支或等待1秒钟后执行time.After
分支,这里用于模拟超时情况。