iamwwcposts / articles

my blog
https://www.chaochaogege.com
12 stars 0 forks source link

Go并发打印数字 #20

Open taikulawo opened 5 years ago

taikulawo commented 5 years ago

其实说白了就是流程控制,现在有三个 goroutine,如果控制他们顺序呢?

具体细节忘了,但好像美团面试官就是这么问的

当时没说明白,要是手写一下让面试官看下,说不定就不会挂掉了...

package main

import (
    "fmt"
    "sync"
)

func main() {
    c1 := make(chan struct{})
    c2 := make(chan struct{})
    group := sync.WaitGroup{}
    group.Add(1)
    go func() {
        fmt.Println("g1")
        c1 <- struct{}{}
    }()

    go func() {
        <- c1
        fmt.Println("g2")
        c2 <- struct{}{}
    }()

    go func() {
        <- c2
        fmt.Println("g3")
        group.Done()
    }()
    group.Wait()
}