005 Golang-channel-practice 打印ABC

第五题 顺序打印ABC

依然是,一个协程打印A,一个协程打印B,一个协程打印C。按照上一题左右括号的例子,我们来试一下这题~

直接上代码:

package main
import (
    "fmt"
    "sync"
)
func main() {
    for {
       times := 1
       c := make(chan struct{})
       d := make(chan struct{})
       var wg sync.WaitGroup
       wg.Add(1)
       go printA(c, times)
       go printB(c, &wg, d)
       go printC(d, &wg)
       wg.Wait()
    }
}
func printA(c chan struct{}, times int) {
    defer close(c)
    for i := 0; i < times; i++ {
       fmt.Print("A")
       c <- struct{}{}
    }
}
func printB(c chan struct{}, wg *sync.WaitGroup, d chan struct{}) {
    for range c {
       fmt.Print("B")
       d <- struct{}{}
    }
    close(d)
}
func printC(d chan struct{}, wg *sync.WaitGroup) {
    defer wg.Done()
    for range d {
       fmt.Print("C")
    }
}

 

 

你可能感兴趣的:(Golang,golang,开发语言)