为什么golang select语句不随机选择一个case
why golang select statement does not randomly choose a case
这与 类似,但我没有从 post 那里得到答案。所以我在这里问。感谢您的回答。
在http://tour.golang.org/concurrency/5中,似乎"case c <- x:"总是准备好的,这意味着这种情况不会阻塞select语句。
基于句子"A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.",当"case <-quit:"也准备好了,select语句应该随机选择"case c <- x:"和"case <-quit:"。但是程序总是进入 "case <-quit:" 的情况。
我还将 select 块更改为如下所示。然后在前 10 次循环中,程序随机打印 1-6,但程序退出一次(第 11 次输出)退出通道的值为 0。
我的问题是,如果就绪案例是随机 select 生成的,那么为什么第 11 个 selection 总是退出案例。
select {
case c <- 1:
x, y = y, x+y
case c <- 2:
x, y = y, x+y
case c <- 3:
x, y = y, x+y
case c <- 4:
x, y = y, x+y
case c <- 5:
x, y = y, x+y
case c <- 6:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
在 case 语句中,您将值发送到 c
(例如 c <- 1
),它会阻塞,直到某些内容将 c 读为 foo := <- c
。当某些内容写入 quit
时,它将遇到 <-quit
位于并从 select 返回的情况。
来自这个例子
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
quit := make(chan struct{})
go func(q chan<- struct{}) {
time.Sleep(5 * time.Second)
q <- struct{}{}
}(quit)
go func(ch chan<- int) {
var x int
for range time.Tick(1 * time.Second) {
c <- x
x++
}
}(c)
for {
select {
case foo := <-c:
fmt.Println("Foo", foo)
case bar := <-c:
fmt.Println("Bar", bar)
case <-quit:
fmt.Println("quit")
return
}
}
}
您可以看到在您的机器上随机打印出的值如下:
$ go run foo.go
Bar 0
Bar 1
Foo 2
Bar 3
quit
$ go run foo.go
Bar 0
Foo 1
Bar 2
Bar 3
quit
这与
在http://tour.golang.org/concurrency/5中,似乎"case c <- x:"总是准备好的,这意味着这种情况不会阻塞select语句。
基于句子"A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.",当"case <-quit:"也准备好了,select语句应该随机选择"case c <- x:"和"case <-quit:"。但是程序总是进入 "case <-quit:" 的情况。
我还将 select 块更改为如下所示。然后在前 10 次循环中,程序随机打印 1-6,但程序退出一次(第 11 次输出)退出通道的值为 0。
我的问题是,如果就绪案例是随机 select 生成的,那么为什么第 11 个 selection 总是退出案例。
select {
case c <- 1:
x, y = y, x+y
case c <- 2:
x, y = y, x+y
case c <- 3:
x, y = y, x+y
case c <- 4:
x, y = y, x+y
case c <- 5:
x, y = y, x+y
case c <- 6:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
在 case 语句中,您将值发送到 c
(例如 c <- 1
),它会阻塞,直到某些内容将 c 读为 foo := <- c
。当某些内容写入 quit
时,它将遇到 <-quit
位于并从 select 返回的情况。
来自这个例子
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
quit := make(chan struct{})
go func(q chan<- struct{}) {
time.Sleep(5 * time.Second)
q <- struct{}{}
}(quit)
go func(ch chan<- int) {
var x int
for range time.Tick(1 * time.Second) {
c <- x
x++
}
}(c)
for {
select {
case foo := <-c:
fmt.Println("Foo", foo)
case bar := <-c:
fmt.Println("Bar", bar)
case <-quit:
fmt.Println("quit")
return
}
}
}
您可以看到在您的机器上随机打印出的值如下:
$ go run foo.go
Bar 0
Bar 1
Foo 2
Bar 3
quit
$ go run foo.go
Bar 0
Foo 1
Bar 2
Bar 3
quit