英文:
About the order of channels
问题
我运行了下面的代码多次,有时在“test2”之后会打印出“test”。为什么会这样呢?我认为“true”首先被发送到“test”。
package main
import "log"
import "time"
func main() {
test := make(chan bool, 1)
test2 := make(chan bool, 1)
go func() {
for {
select {
case <-test:
log.Println("test")
case <-test2:
log.Println("test2")
}
}
}()
time.Sleep(3 * time.Second)
test <- true
test2 <- true
time.Sleep(1)
}
编辑于2014/7/27:
阅读了这篇文章后,我认为每个"test <- true"和"test2 <- true"都可以是"happens-before"、"happens-after"或者"happens-concurrently"。
英文:
I ran the code below several times and sometimes "test" was printed after "test2".<br>
Why is that?<br>
I think "true" is sent to "test" first.<br>
package main
import "log"
import "time"
func main() {
test := make(chan bool, 1)
test2 := make(chan bool, 1)
go func() {
for {
select {
case <-test:
log.Println("test")
case <-test2:
log.Println("test2")
}
}
}()
time.Sleep(3 * time.Second)
test <- true
test2 <- true
time.Sleep(1)
}
Edited 2014/7/27:<br>
After reading the article, I think that each of "test <- true" and "test2 <- true" could be "happens-before" or "happens-after" or also "happens-concurrently".
答案1
得分: 1
如果可以进行一个或多个通信,则通过均匀伪随机选择选择一个可以进行的通信。您正在看到一个均匀伪随机选择。
英文:
"If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection." You are seeing a uniform pseudo-random selection.
> 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.
>
> Since communication on nil channels can never proceed, a select with
> only nil channels and no default case blocks forever.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论