3个函数分别打印cat、dog、fish,要求每个函数都要起一个goroutine,按照cat、dog、fish顺序打印在屏幕上100次。

317 阅读1分钟
package main

import (
    "fmt"
    "sync"
)

var countNum = 100

//3个函数分别打印cat、dog、fish,要求每个函数都要起一个goroutine,按照cat、dog、fish顺序打印在屏幕上10次
func main() {
    var wg sync.WaitGroup

    dogCh := make(chan struct{}, 1)
    defer close(dogCh)
    catCh := make(chan struct{}, 1)
    defer close(catCh)
    fishCh := make(chan struct{}, 1)
    defer close(fishCh)

    wg.Add(3)
    go catPrint(&wg, &catCh, &dogCh)
    go dogPrint(&wg, &dogCh, &fishCh)
    go fishPrint(&wg, &fishCh, &catCh)

    catCh <- struct{}{}
    wg.Wait()
}
func catPrint(wg *sync.WaitGroup, catCh *chan struct{}, dogCh *chan struct{}) {
    count := 0
    for {
        if count >= countNum {
            wg.Done()
            //fmt.Println("cat quit")
            return
        }
        <-*catCh
        fmt.Println("cat", count+1)
        count++
        *dogCh <- struct{}{}
    }
}

func dogPrint(wg *sync.WaitGroup, dogCh *chan struct{}, fishCh *chan struct{}) {
    count := 0
    for {
        if count >= countNum {
            wg.Done()
            //fmt.Println("dog quit")
            return
        }
        <-*dogCh
        fmt.Println("dog")
        count++
        *fishCh <- struct{}{}
    }
}

func fishPrint(wg *sync.WaitGroup, dogCh *chan struct{}, catCh *chan struct{}) {
    count := 0
    for {
        if count >= countNum {
            wg.Done()
            //fmt.Println("fish quit")
            return
        }
        <-*dogCh
        fmt.Println("fish")
        count++
        *catCh <- struct{}{}
    }
}