package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var wg sync.WaitGroup
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
court := make(chan int)
wg.Add(2)
go player("A", court)
go player("B", court)
court <- 1
wg.Wait()
}
func player(name string, court chan int) {
defer wg.Done()
for {
ball, ok := <-court //走到这里就会阻塞 是吧?
if !ok { //通道关闭
fmt.Printf("Player %s Won\n", name)
return
}
n := rand.Intn(100)
if n%13 == 0 {
fmt.Printf("Player %s missed\n", name)
close(court)
return
}
fmt.Printf("Player %s Hit %d \n", name, ball)
ball++
court <- ball
}
}
每次打印都是 B 所在的协程先触发