channle 按照顺序输出

按照 dog cat fish 的顺序输出,要求使用 channel 完成

结果如下图:

cat     dog     fish    cat     dog     fish    ...

代码

package main

import (
    "fmt"
    "sync"
)

func showName(name string, ch1, ch2 chan struct{}) {
    <-ch1
    fmt.Printf("%s\t", name)
    ch2 <- struct{}{}
}

func main() {

    var wg sync.WaitGroup

    ch1 := make(chan struct{}, 1)
    ch2 := make(chan struct{}, 1)
    ch3 := make(chan struct{}, 1)
    ch3 <- struct{}{}

    for i := 0; i < 100; i++ {
        go func() {
            wg.Add(1)
            showName("cat", ch3, ch1)
            showName("dog", ch1, ch2)
            showName("fish", ch2, ch3)
            wg.Done()
        }()

    }
    wg.Wait()
}
作者:admin  创建时间:2022-05-18 09:22
最后编辑:admin  更新时间:2023-04-10 15:46