package main

import (
    "fmt"
    "sync"
)

func printWord(word string, count int, currentChan, nextChan chan struct{}, wg *sync.WaitGroup) {
    var i = 0
    for i < count {
        if _, ok := <-currentChan; ok {
            fmt.Println(word)
            i++
            // 最后一次打印 fish 时, 也会往 dogChan 发送数据,所以使用有缓冲通道,接收最后一次多余的发送
            nextChan <- struct{}{}
        }
    }

    wg.Done()
}

func main() {
    var (
        wg    sync.WaitGroup
        count = 100

        // 有缓冲通道
        // 为什么使用 struct{} channel 请参考 https://www.vicw.com/groups/code_monkey/topics/396
        dogChan  = make(chan struct{}, 1)
        catChan  = make(chan struct{}, 1)
        fishChan = make(chan struct{}, 1)
    )

    wg.Add(3)

    // 按照 dog, cat, fish 顺序打印100遍
    go printWord("dog", count, dogChan, catChan, &wg)
    go printWord("cat", count, catChan, fishChan, &wg)
    go printWord("fish", count, fishChan, dogChan, &wg)

    dogChan <- struct{}{}

    wg.Wait()
}
0条评论 顺序楼层
请先登录再回复