gpt4 book ai didi

去 <-chan overhead

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

一段时间以来,我一直在尝试理解 Go 中的 channel 。但有一件事让我感到奇怪。当你打电话时究竟发生了什么,

for {
select {
case <-chan:
}
}

它是否每次迭代都检查 chan 是否有更新?它与普通 case i = int:case atomic.LoadUint64() = uint64: 在性能方面相比如何?

最佳答案

The Go Programming Language Specification

Select statements

Execution of a "select" statement proceeds in several steps:

  1. For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.
  2. If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.
  3. Unless the selected case is the default case, the respective communication operation is executed.
  4. If the selected case is a RecvStmt with a short variable declaration or an assignment, the left-hand side expressions are evaluated and the received value (or values) are assigned.
  5. The statement list of the selected case is executed.

select语句行为在 The Go Programming Language Specification 中定义。 <-chan被评估一次。

For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement.

关于去 <-chan overhead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413403/

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