douyan6958
2013-10-03 00:10
浏览 146
已采纳

如何在Golang中使用RWMutex?

type Stat struct {
    counters     map[string]*int64
    countersLock sync.RWMutex
    averages     map[string]*int64
    averagesLock sync.RWMutex
}

It is called below

func (s *Stat) Count(name string) {
    s.countersLock.RLock()
    counter := s.counters[name]
    s.countersLock.RUnlock()
    if counter != nil {
        atomic.AddInt64(counter, int64(1))
        return
    }
}

My understanding is that we first lock the receiver s (which is a type Stat) and then we add to it if the counter does exist.

Questions:

Q1: why do we need to lock it? What does RWMutex even mean?

Q2: s.countersLock.RLock() - does this lock up the entire receiver s or only the counters field in type Stat?

Q3: s.countersLock.RLock() - does this lock up the averages field?

Q4: Why should we use RWMutex? I thought channel was the preferred way to handle concurrency in Golang?

Q5: What is this atomic.AddInt64. Why do we need atomic in this case?

Q6: Why would we unlock right before we add to it?

图片转代码服务由CSDN问答提供 功能建议

  type Stat struct {
 counters map [string] * int64 
 countersLock sync.RWMutex 
 平均值map [string] * int64 
平均值锁同步。RWMutex
} 
   
 
 

以下称为

  func(s * Stat)Count(名称字符串){
 s.countersLock.RLock()
计数器:= s.counters [名称] 
 s.countersLock.RUnlock()
如果counter!= nil {  
 atomic.AddInt64(counter,int64(1))
 return 
} 
} 
   
 
 

我的理解是,我们首先锁定了接收者s(

问题:

问题1:为什么我们需要锁定 它? RWMutex 到底是什么意思?

Q2: s.countersLock.RLock()-这会锁定整个接收器吗?

Q3: s.countersLock.RLock()-这是否会锁定平均值字段?

问题4:我们为什么要使用 RWMutex ? 我以为channel是处理Golang中并发的首选方法?

Q5:这是什么 .atomic.AddInt64 。 为什么在这种情况下我们需要原子的?

问题6:为什么要在添加之前立即解锁?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题