去哪儿面试题 (Golang实现)多线程顺序输出1-75

FredricZhu ·
``` type Num struct { val int mu sync.RWMutex } func main() { num := new(Num) wg := sync.WaitGroup{} add := func() { num.mu.Lock() num.val++ fmt.Println(num.val) num.mu.Unlock() wg.Done() } for i := 0; i < 75; i++ { wg.Add(1) go add() } wg.Wait() } ```
#8
更多评论
``` var a struct { Mu sync.RWMutex Count int } var wg sync.WaitGroup func main() { wg = sync.WaitGroup{} wg.Add(75) for i:=1; i<=75; i++ { go Add() } wg.Wait() } func Add() { defer wg.Done() a.Mu.Lock() a.Count++ fmt.Println(a.Count) a.Mu.Unlock() } ```
#1
输出结果不稳定,也就是说结果不对
#2