【发布时间】:2020-02-02 23:47:56
【问题描述】:
我正在 YouTube 上观看有关并发模式的视频。 有一个乒乓球的例子:
type Ball struct{ hits int }
func main() {
table := make(chan *Ball)
go player("ping", table)
go player("pong", table)
table <- new(Ball)
time.Sleep(1 * time.Second)
<-table
}
func player(name string, table chan *Ball) {
for {
ball := <-table
ball.hits++
fmt.Println(name, ball.hits)
time.Sleep(100 * time.Millisecond)
table <- ball
}
}
应该给出结果:
Ping 1
Pong 2
Ping 3
Pong 4
...
但是,如果我删除播放器的一个 goroutine,例如“pong”:
// go player("pong", table) // remove this line
我只得到一个结果:
Ping 1
我不明白func播放器中有一个for循环,并且'table'通道将Ball输出给ball,在循环结束时,我们将Ball放回通道表。为什么玩家“ping”不能自己玩?
【问题讨论】:
-
也许可以先试试“Tour of Go”,这在并发部分有介绍:tour.golang.org/concurrency/2