加sync.WaitGroup 会等待WaitGroup内的线程执行完毕后再执行后面的代码,例如
var fmtMap sync.Map
func producer(ch chan<- int) {
defer waitGroup.Done()
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
fmtMap.Store("A","A")
}
func consumer(ch <-chan int){
defer waitGroup.Done()
for {
select {
case _, ok:=<-ch:
if ok == false {
goto done
}
}
}
done:
fmtMap.Store("B","B")
}
var waitGroup = new(sync.WaitGroup)
func waitTest() {
ch := make(chan int, 5)
waitGroup.Add(2)
go producer(ch)
go consumer(ch)
waitGroup.Wait()
fmt.Println(fmtMap)
}
func main() {
go waitTest()
router := gin.Default()
router.Run(":8031")
}
会输出
如果没加sync.WaitGroup则会打印nil,因为没等待开启的协程执行完毕就已经执行打印语句了