问题内容
给定一个通道切片([]chan{}),如何实现我们从通道数组中接受这些消息。
我考虑以下两种方法,但它们可以解决我的问题:
- 我们可以使用“select”,但是切片的长度不固定,所以case的数量也不固定。
- 我们可以遍历切片,但是当收不到消息时会导致阻塞。
正确答案
您可以使用反映包来选择动态数字频道。
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
// Create a slice of channels
channels := make([]chan string, 5)
// Initialize the channels
for i := range channels {
channels[i] = make(chan string)
}
// Send messages to the channels
go func() {
for _, ch := range channels {
time.Sleep(time.Second)
ch <- "hello"
}
}()
// Use reflect.Select to select on a set of channels in the slice
for {
cases := make([]reflect.SelectCase, len(channels))
for i, ch := range channels {
cases[i] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
}
}
// Wait for a message to be received on one of the channels
i, v, ok := reflect.Select(cases)
if !ok {
fmt.Println("Channel closed")
continue
}
// Print the received message and the index of the channel
fmt.Printf("Received %q from channel %d\n", v.Interface(), i)
}
}
今天关于《下面的场景中如何实现这些goroutines的通信》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注公众号!