一个结构体中如果有map类型的属性时,为保证读写时的互斥添加RWMutex了,但读出时因为等待问题出现了取不到数据(打印-1)情况,请问如何解决,代码如下:
```golang
type UserAges struct {
ages map[string]int
sync.RWMutex
}
func (ua *UserAges) Add(name string, age int) {
ua.Lock()
defer ua.Unlock()
ua.ages[name] = age
}
func (ua *UserAges) Get(name string) int {
ua.RLock()
defer ua.RUnlock()
if age, ok := ua.ages[name]; ok {
return age
}
return -1
}
func main() {
ua := &UserAges{ages: make(map[string]int)}
for i := 0; i < 10; i++ {
go func(i int) {
ua.Add("xiaohong"+fmt.Sprintf("%d", i), i)
}(i)
}
for i := 0; i < 10; i++ {
go func(i int) {
fmt.Println(ua.Get("xiaohong" + fmt.Sprintf("%d", i)))
}(i)
}
<-time.After(time.Second * 2)
}
```
有疑问加站长微信联系(非本文作者)