gpt4 book ai didi

go - 如何收听N个 channel ? (动态选择语句)

转载 作者:IT王子 更新时间:2023-10-29 02:22:01 26 4
gpt4 key购买 nike

要开始执行两个 goroutine 的无限循环,我可以使用下面的代码:

收到消息后,它将启动一个新的 goroutine 并一直运行下去。

c1 := make(chan string)
c2 := make(chan string)

go DoStuff(c1, 5)
go DoStuff(c2, 2)

for ; true; {
select {
case msg1 := <-c1:
fmt.Println("received ", msg1)
go DoStuff(c1, 1)
case msg2 := <-c2:
fmt.Println("received ", msg2)
go DoStuff(c2, 9)
}
}

我现在希望 N 个 goroutine 具有相同的行为,但在这种情况下 select 语句将如何显示?

这是我开始的代码位,但我对如何编写 select 语句的代码感到困惑

numChans := 2

//I keep the channels in this slice, and want to "loop" over them in the select statemnt
var chans = [] chan string{}

for i:=0;i<numChans;i++{
tmp := make(chan string);
chans = append(chans, tmp);
go DoStuff(tmp, i + 1)

//How shall the select statment be coded for this case?
for ; true; {
select {
case msg1 := <-c1:
fmt.Println("received ", msg1)
go DoStuff(c1, 1)
case msg2 := <-c2:
fmt.Println("received ", msg2)
go DoStuff(c2, 9)
}
}

最佳答案

您可以使用 Select 执行此操作来自 reflect 的函数包裹:

func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)

Select executes a select operation described by the list of cases. Like the Go select statement, it blocks until at least one of the cases can proceed, makes a uniform pseudo-random choice, and then executes that case. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the value corresponds to a send on the channel (as opposed to a zero value received because the channel is closed).

您传入一组 SelectCase 结构,这些结构标识要选择的 channel 、操作的方向以及在发送操作的情况下要发送的值。

所以你可以这样做:

cases := make([]reflect.SelectCase, len(chans))
for i, ch := range chans {
cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}
}
chosen, value, ok := reflect.Select(cases)
// ok will be true if the channel has not been closed.
ch := chans[chosen]
msg := value.String()

您可以在这里尝试一个更充实的示例:http://play.golang.org/p/8zwvSk4kjx

关于go - 如何收听N个 channel ? (动态选择语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com