选择情况选择在geth 1.9.25v中。

huangapple go评论84阅读模式
英文:

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.nextm.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(&quot;discmix Addsource : &quot;, n.ID())
		select {
		case s.next &lt;- n:
			fmt.Println(&quot;s.next &lt;- n :&quot;, n.ID())
		case m.fromAny &lt;- n:
			fmt.Println(&quot;m.fromAny &lt;- n :&quot;, n.ID())
		case &lt;-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 &lt;- n is being picked more frequently in comparison to case m.fromAny &lt;- 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的行为。

Go Tour的select链接

所以,select会阻塞直到其中一个case可以执行,然后执行该case。如果有多个case都准备好了,它会随机选择一个。

而且,这不仅仅涉及到n,还涉及到s.nextm.fromAny

让我们考虑这两种情况:

// 为了选择这个case,s.next应该准备好
case s.next <- n


// 为了选择这个case,m.fromAny应该准备好
case m.fromAny <- n

所以,假设ns.nextm.fromAny同时准备好了,任何一个case都可能被随机选择(在定义中也有描述)。

n是可用的,所以取决于接收通道:s.nextm.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 &lt;- n


// For this case to be selected m.fromAny should be ready
case m.fromAny &lt;- 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.

huangapple
  • 本文由 发表于 2021年7月22日 14:55:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/68480409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定