无缓冲chan

通过goroutine之间同步数据,来模拟接力比赛。4个跑步者绕赛道轮流跑。第二个、第三个、第四个要接到前一个跑步接力棒才能跑。在同步接力棒时,参与接力的两个跑步者必须在同一时刻做好准备。

package main

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

var wg sync.WaitGroup

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

func main() {
    //创建通道,接力棒
    baton := make(chan int)
    wg.Add(1)  //判断第四位跑步者是否跑完
    go Runner(baton)  //第一位跑步者拿到接力棒
    baton <- 1   //开始比赛
    wg.Wait()  //等待比赛结束
}

func Runner(baton chan int) {
    var newRunner int  
    runner := <-baton  //等待接力棒
    //开始跑步
    fmt.Printf("Runner %d Running With Baton\n", runner)

    //创建下一位跑步者
    if runner != 4 {
        newRunner = runner + 1
        fmt.Printf("Runner %d To the Line\n", newRunner)
        go Runner(baton)  //下一位跑步者获取接力棒
    }

    //绕圈跑步
    time.Sleep(100 * time.Millisecond)

    //比赛结束?
    if runner == 4 {
        fmt.Printf("Runner %d Finished,Race over\n", runner)
        wg.Done()  //通知main函数第四位跑步者跑完
        return
    }

    //传递接力棒给下一位跑步者
    fmt.Printf("Runner %d Exchange With Runner %d\n", runner, newRunner)
    baton <- newRunner  //传递接力棒给下一位跑步者

}

你可能感兴趣的:(golang)