当前位置: > > > > 下面的场景中如何实现这些goroutines的通信
下面的场景中如何实现这些goroutines的通信
来源:stackoverflow
2024-04-24 17:42:23
0浏览
收藏
一分耕耘,一分收获!既然都打开这篇《下面的场景中如何实现这些goroutines的通信》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
问题内容
给定一个通道切片([]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的通信》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注米云公众号!
