【发布时间】:2018-03-21 02:58:32
【问题描述】:
我有一个看似无辜的包,它只是切片并用 RWMutex 保护它。但是,当我运行它时,它仍然抱怨竞争条件。我究竟做错了什么? (playground)
type Ids struct {
e []int64
sync.RWMutex
}
func (i *Ids) Read() []int64 {
i.RLock()
defer i.RUnlock()
return i.e
}
func (i *Ids) Append(int int64) {
i.Lock()
defer i.Unlock()
i.e = append(i.e, int)
}
func main() {
t := &Ids{e: make([]int64, 1)}
for i := 0; i < 100; i++ {
go func() {
fmt.Printf("%v\n", t.Read())
}()
go func() {
t.Append(int64(i))
}()
}
time.Sleep(time.Second * 10)
}
当使用-race 运行时,它会返回(除其他外):
==================
WARNING: DATA RACE
Read at 0x00c4200a0010 by goroutine 7:
main.main.func2()
.../main.go:38 +0x38
Previous write at 0x00c4200a0010 by main goroutine:
main.main()
.../main.go:32 +0x197
Goroutine 7 (running) created at:
main.main()
.../main.go:37 +0x173
==================
【问题讨论】:
标签: go concurrency mutex race-condition