gpt4 book ai didi

go - golang select 语句中案例与默认值的优先级

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

我有一个包含多个 goroutine 的应用程序正在运行 for 循环,并且需要一种方法来指示这些 for 循环中断,并测试是否发生超时情况.我正在研究使用带有 select 语句的共享 channel 来完成此操作,如下所示:

// elsewhere in the code, this channel is created, and passed below
done := make(chan struct{})
time.AfterFunc(timeout, func() { close(done) })
...
go func() {
Loop:
for {
select {
case <-done:
break Loop
default:
foo()
time.Sleep(1 * time.Second)
}
}
select {
case <-done:
panic("timed out!")
default:
// ok
}
}()

这是实现此目标的有效方法吗?我最担心的是,所选择的 select 分支可能是不确定的,因此即使 之一,也可能会选择 default >案例已准备就绪。这可能吗?是否有任何文档说明匹配的 case 保证优先于 default。问题是上面的 for 循环可能会在 done 关闭和/或报告成功后循环多次,即使发生超时也是如此。

最佳答案

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.

"What I'm most concerned about is that the branch of a select that is chosen could be non-deterministic, so that default may be chosen even if one of the cases is ready. Is this possible?"

没有。请参阅 select 规范的第 2 步。

关于go - golang select 语句中案例与默认值的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45580151/

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