如何解决多个 Go 例程从同一通道读取
嗨,我的控制通道(各种)有问题。
我的程序的本质:
- 我不知道我将在运行时运行多少个 go 例程
- 我需要在设定的时间重新启动这些 go 例程,但是,它们也可能会出错(然后重新启动),因此它们的时间是不可预测的。
- 这些 go 例程将把消息放到一个通道上。
所以我所做的是创建了一个简单的随机消息生成器来将消息放到一个频道上。 当计时器到时(测试的随机持续时间)我将一条消息放到一个控制通道,这是一个结构有效载荷,所以我知道有一个关闭信号并且哪个去这是例行公事;实际上,在再次开始 go 例程之前,我会做一些我需要做的其他事情。
我的问题是:
- 我在我的reflect.Select 循环中收到控制消息
- 我没有(或无法)在我的 randmsgs() 循环中接收它
因此我无法停止我的 randmsgs() go 例程。
我相信我理解多个 go 例程可以从单个通道读取是正确的,因此我认为我误解了 reflect.SelectCases 如何适应所有这些。
我的代码:
package main
import (
"fmt"
"math/rand"
"reflect"
"time"
)
type testing struct {
control bool
market string
}
func main() {
rand.Seed(time.Now().UnixNano())
// explicitly define chanids for tests.
var chanids []string = []string{"GR I","GR II","GR III","GR IV"}
stream := make(chan string)
control := make([]chan testing,len(chanids))
reflectCases := make([]reflect.SelectCase,len(chanids)+1)
// MAKE REFLECT SELECTS FOR 4 CONTROL CHANS AND 1 DATA CHANNEL
for i := range chanids {
control[i] = make(chan testing)
reflectCases[i] = reflect.SelectCase{Dir: reflect.SelectRecv,Chan: reflect.ValueOf(control[i])}
}
reflectCases[4] = reflect.SelectCase{Dir: reflect.SelectRecv,Chan: reflect.ValueOf(stream)}
// START GO ROUTINES
for i,val := range chanids {
runningFunc(control[i],val,stream,1+rand.Intn(30-1))
}
// READ DATA
for {
o,recieved,ok := reflect.Select(reflectCases)
if !ok {
fmt.Println("You really buggered this one up...")
}
ty,err := recieved.Interface().(testing)
if err == true {
fmt.Printf("Read from: %v,and recieved close signal from: %s\n",o,ty.market)
// close control & stream here.
} else {
ty := recieved.Interface().(string)
fmt.Printf("Read from: %v,and recieved value from: %s\n",ty)
}
}
}
// THE GO ROUTINES - TIMER AND RANDMSGS
func runningFunc(q chan testing,chanid string,stream chan string,dur int) {
go timer(q,dur,chanid)
go randmsgs(q,chanid,stream)
}
func timer(q chan testing,t int,message string) {
for t > 0 {
time.Sleep(time.Second)
t--
}
q <- testing{true,message}
}
func randmsgs(q chan testing,stream chan string) {
for {
select {
case <-q:
fmt.Println("Just sitting by the mailbox. :(")
return
default:
secondsToWait := 1 + rand.Intn(5-1)
time.Sleep(time.Second * time.Duration(secondsToWait))
stream <- fmt.Sprintf("%s: %d",secondsToWait)
}
}
}
我为文字墙道歉,但我完全没有想法:(!
K/问候, C.
解决方法
您在后半部分的频道 q
与第一部分的 control[0...3]
相同。
您正在运行的 reflect.Select
也从所有这些通道读取,没有延迟。
我认为问题归结为您的 reflect.Select
运行速度太快并立即“窃取”了所有频道输出。这就是 randmsgs
永远无法读取消息的原因。
您会注意到,如果您从 randmsgs
中删除 default case,该函数能够(潜在地)读取来自 q
的一些消息。
select {
case <-q:
fmt.Println("Just sitting by the mailbox. :(")
return
}
这是因为现在它没有延迟地运行,它总是在等待 q
上的消息,因此有机会在比赛中击败 reflect.Select
。
如果你在多个 goroutine 中从同一个通道读取,那么传递的数据将简单地去任何 goroutine 首先读取它。
这个计划似乎只是一个实验/学习体验,但我会提出一些可能有帮助的批评。
-
同样,如果两个 goroutine 执行不同的任务,通常不会有多个 goroutine 从同一通道读取。您正在创建一个关于哪个 goroutine 首先获取数据的非确定性竞争。
-
其次,这是一个常见的初学者使用 select 的反模式,您应该避免:
for {
select {
case v := <-myChan:
doSomething(v)
default:
// Oh no,there wasn't anything! Guess we have to wait and try again.
time.Sleep(time.Second)
}
这段代码是多余的,因为 select
已经以这样一种方式运行:如果最初没有准备好任何案例,它将等待任何案例准备好,然后继续处理那个案例。此 default: sleep
有效地使您的选择循环变慢,但实际等待频道的时间却更少(因为 99.999...% 的时间花在 time.Sleep
上)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。