英文:
select case selection in geth 1.9.25v
问题
func (m *FairMix) runSource(closed chan struct{}, s *mixSource) {
defer m.wg.Done()
defer close(s.next)
for s.it.Next() {
n := s.it.Node()
fmt.Println("discmix Addsource: ", n.ID())
select {
case s.next <- n:
fmt.Println("s.next <- n:", n.ID())
case m.fromAny <- n:
fmt.Println("m.fromAny <- n:", n.ID())
case <-closed:
return
}
}
}
这是以太坊 geth 1.9.25v 的代码。
在 select
操作中,这两个变量 s.next
和 m.fromAny
都在等待 n
。
但是当我运行程序时,case s.next <- n
被选择的次数比 case m.fromAny <- n
更频繁。
我可以知道哪个 case 会先被选择吗?如果有多个 case 都准备好了,是否有一种选择 case 的算法?
英文:
func (m *FairMix) runSource(closed chan struct{}, s *mixSource) {
defer m.wg.Done()
defer close(s.next)
for s.it.Next() {
n := s.it.Node()
fmt.Println("discmix Addsource : ", n.ID())
select {
case s.next <- n:
fmt.Println("s.next <- n :", n.ID())
case m.fromAny <- n:
fmt.Println("m.fromAny <- n :", n.ID())
case <-closed:
return
}
}
}
This is the Ethereum geth 1.9.25v code.
In the select
operation, these two s.next
& m.fromAny
variables both are waiting for n
.
But when I run the program, case s.next <- n
is being picked more frequently in comparison to case m.fromAny <- n
.
Can I know which case would be selected first? Is there some algorithm of picking the cases if multiple cases are ready?
答案1
得分: 0
我建议你参考Go Tour。在Go Tour中,他们有易于理解的实践场景,涵盖了select
的行为。
所以,select
会阻塞直到其中一个case可以执行,然后执行该case。如果有多个case都准备好了,它会随机选择一个。
而且,这不仅仅涉及到n
,还涉及到s.next
和m.fromAny
。
让我们考虑这两种情况:
// 为了选择这个case,s.next应该准备好
case s.next <- n
// 为了选择这个case,m.fromAny应该准备好
case m.fromAny <- n
所以,假设n
、s.next
和m.fromAny
同时准备好了,任何一个case都可能被随机选择(在定义中也有描述)。
n
是可用的,所以取决于接收通道:s.next
和m.fromAny
。
因此,如果有多个case都准备好了,我们无法确定哪个case会被选择。
英文:
I'd recommend you the Go Tour. In Go Tour, they have easy to understand hands-on playground where they covered the behavior of select
as well.
Link to Go Tour on select
So, a select
blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
And, it's not just about n
but also about s.next
and m.fromAny
.
So, let's consider these two cases:
// For this case to be selected s.next should be ready
case s.next <- n
// For this case to be selected m.fromAny should be ready
case m.fromAny <- n
So, suppose s.next
and m.fromAny
both are ready at the same time, any case could be selected at random (described in the definition as well).
n
is available, so it depends on the receiver channels: s.next
and m.fromAny
.
Hence, we can't decide for sure which case would be selected if multiple are ready.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论