1. 使用协程编写程序,按顺序打印 cat、dog、fish ,依次打印十次

package main

import (
    "fmt"
    "sync"
    "time"
)

var wg sync.WaitGroup

func main() {
    ch1 := make(chan struct{}, 1)
    ch2 := make(chan struct{}, 1)
    ch3 := make(chan struct{}, 1)

    wg.Add(3)
    start := time.Now().Unix()
    // 这里的 三个必须都是10,否则有的 channel 关闭,再进行写入报错
    total := 10
    // 触发动作
    ch1 <- struct{}{}
    go handle("CAT", total, ch1, ch2)
    go handle("DOG", total, ch2, ch3)
    go handle("FISH", total, ch3, ch1)
    wg.Wait()
    end := time.Now().Unix()
    fmt.Printf("cost:%d", end-start)
}

// go goroutine
func handle(name string, nums int, inputChan chan struct{}, outputChan chan struct{}) {
    defer wg.Done()
    for i := 0; i < nums; i++ {
        // 这里休眠可以感受到 3个 goroutine 的并发执行,而不是串行,1秒中,输出三个
        time.Sleep(1 * time.Second)
        select {
        case <-inputChan:
            fmt.Printf("%s \n", name)
            outputChan <- struct{}{}
        }
    }
}

1 对 “常见编程题”的想法;

发表回复