无缓冲通道

通道是goroutine之间的安全通讯机制。是阻塞/同步机制

package main

import (
"fmt"
"math/rand"
"sync"
"time"
)

var wg sync.WaitGroup

func init() {
rand.Seed(time.Now().UnixNano())
}

func main() {
cc := make(chan byte)

wg.Add(2)

// 运动员就绪
go playball("ping jie", cc)
go playball("luo ge", cc)

cc <- 1

wg.Wait()
}

// 运动员
func playball(name string, cc chan byte) {
defer wg.Done()

for {
// 接球
ball, ok := <-cc
if !ok {
fmt.Printf("Player %s Won\n", name)
return
}

// 结束条件判断
n := rand.Intn(50)
if n%9 == 0 {
fmt.Printf("Player %s Missed\n", name)
close(cc)
return
}

// 发球
fmt.Printf("Player %s Hit %d\n", name, ball)
cc <- ball
}
}