【发布时间】:2013-11-28 07:55:11
【问题描述】:
要开始执行两个 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)
}
}
【问题讨论】:
-
我认为你想要的是频道多路复用。 golang.org/doc/effective_go.html#chan_of_chan 基本上,您只有一个频道可以收听,然后有多个子频道汇入主频道。相关 SO 问题:stackoverflow.com/questions/10979608/…
标签: go