我正在閱讀 Katherine Cox-Buday 的《Concurrency in Go: Tools and Techniques for Developers》。到目前為止,我讀起來(lái)很棒,在書中偶然發(fā)現(xiàn)了一個(gè)我想測(cè)試的代碼塊。當(dāng)我在IDE中運(yùn)行它時(shí),我得到了不同的結(jié)果,我不知道為什么。這是代碼:package mainimport ("fmt""sync")func main() {var count intvar lock sync.Mutexincrement := func() { lock.Lock() defer lock.Unlock() count++ fmt.Printf("Incrementing: %d\n", count)}decrement := func() { lock.Lock() defer lock.Unlock() count-- fmt.Printf("Decrementing: %d\n", count)}// Incrementvar arithmetic sync.WaitGroupfor i := 0; i <= 5; i++ { arithmetic.Add(1) go func() { defer arithmetic.Done() increment() }()}// Decrementfor i := 0; i <= 5; i++ { arithmetic.Add(1) go func() { defer arithmetic.Done() decrement() }()}arithmetic.Wait()fmt.Println("Arithmetic complete.")}我得到這個(gè)結(jié)果:$ go run main.goIncrementing: 1Incrementing: 2Incrementing: 3Incrementing: 4Incrementing: 5Incrementing: 6Decrementing: 5Decrementing: 4Decrementing: 3Decrementing: 2Decrementing: 1Decrementing: 0Arithmetic complete.而在書中,我應(yīng)該有這樣的結(jié)果:Decrementing: -1Incrementing: 0Decrementing: -1Incrementing: 0Decrementing: -1Decrementing: -2Decrementing: -3Incrementing: -2Decrementing: -3Incrementing: -2Incrementing: -1Incrementing: 0Arithmetic complete.有人可以為我澄清一下嗎?
無(wú)法獲得與 Go 書中的并發(fā)性相同的結(jié)果示例代碼
慕田峪7331174
2022-08-09 20:45:27