1 回答
TA贡献1836条经验 获得超13个赞
它有效,但通常是个坏主意(tm)
你未来的软件维护者会因此讨厌你
请注意,如果这些循环不完全相同,那么当主 goroutine 由于没有其他人写入或读取而阻塞时,应用程序将崩溃
package main
import (
"fmt"
)
func main() {
c := make(chan int)
go func() {
for x := 0; x < 5; x++ {
var i int
select {
case c <- 1:
i = <-c
case i = <-c:
c <- 1
}
fmt.Println(" A - Written 1 red ", i)
}
}()
for x := 0; x < 5; x++ {
var i int
select {
case c <- 2:
i = <-c
case i = <-c:
c <- 2
}
fmt.Println(" B - Written 2 red ", i)
}
}
输出:
B - Written 2 red 1
A - Written 1 red 2
B - Written 2 red 1
A - Written 1 red 2
B - Written 2 red 1
A - Written 1 red 2
B - Written 2 red 1
A - Written 1 red 2
B - Written 2 red 1
Program exited.
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报