How to use RWMutex?

Issue

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?

Solution

Questions:

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

RW stands for Read/Write. CF doc: http://golang.org/pkg/sync/#RWMutex.

We need to lock it to prevent other routines/thread to change the value while we process it.

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

As a mutex, the lock occurs only when you call the RLock() function. If any other goroutine already called the WLock(), then it blocks. You can call any number of RLock() within the same goroutine, it won’t lock.

So it does not lock any other fields, not even s.counters. In your example, you lock the map lookup to find the correct counter.

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

No, as said in Q2, a RLock locks only himself.

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

Channel is very useful but sometimes it is not enough and sometimes it does not make sense.

Here, as you lock the map access, a mutex makes sense. With a chan, you’d have to have a buffered chan of 1, send before and receive after. Not very intuitive.

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

This function will increment the given variable in an atomic way. In your case, you have a race condition: counter is a pointer and the actual variable can be destroyed after the release of the lock and before the call to atomic.AddInt64.
If you are not familiar with this kind of things, I’d advise you to stick with Mutexes and do all processing you need in between the lock/unlock.

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

You should not.

I don’t know what you are trying to do, but here is a (simple) example: https://play.golang.org/p/cVFPB-05dw

Answered By – creack

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.