2 回答

TA貢獻1805條經驗 獲得超10個贊
使用不當sync.WaitGroup是導致您出現競爭狀況的原因。其中任何一個都應該正常工作:
func (outer *outer) modify(wg *sync.WaitGroup) {
outer.Lock()
outer.num = outer.num + 1
outer.Unlock()
wg.Done()
}
func (outer *outer) modify(wg *sync.WaitGroup) {
outer.Lock()
defer wg.Done()
defer outer.Unlock()
outer.num = outer.num + 1
}
wg.Done()應該在解鎖互斥鎖之后調用(延遲調用以 LIFO 方式進行),因為之前調用它會導致調用Printf()與最后一個outer.Unlock()調用競爭以訪問outer.

TA貢獻1891條經驗 獲得超3個贊
package main
import (
"fmt"
"sync"
)
type outer struct {
*sync.Mutex
num int
foo string
}
func (outer *outer) modify(wg *sync.WaitGroup) {
outer.Lock()
defer outer.Unlock()
outer.num++
wg.Done()
}
func main() {
outer := outer{
Mutex: &sync.Mutex{},
num: 2,
foo: "hi",
}
w := &sync.WaitGroup{}
for j := 0; j < 5000; j++ {
w.Add(1)
go outer.modify(w)
}
w.Wait()
fmt.Printf("Final is %+v", outer)
}
將sync.Mutex 更改為指針。
我認為這是由于sync.Mutex 在您的版本中很有價值
- 2 回答
- 0 關注
- 143 瀏覽
添加回答
舉報