Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
936 views
in Technique[技术] by (71.8m points)

go - How to use RWMutex in Golang?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...