Go并发打印数字

作者:taikulawo创建时间:2019-09-17字数统计:415预计阅读需要1分钟

#Go

其实说白了就是流程控制,现在有三个 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()
}
0 comments
Anonymous
Markdown is supported

Be the first guy leaving a comment!