Member-only story

Is RWMutex better than Mutex in Go?

the korean guy
5 min readAug 25, 2024

--

In Go, there are two main methods for implementing locking. The first is to use sync.Mutex with its Lock and Unlock methods. This method ensures mutual exclusion by allowing only one goroutine to access a critical section of code at a time.

The difference between sync.Mutex and sync.RWMutex is precisely this:

  • sync.Mutex: Simple and provides exclusive access to a critical section, blocking all other access when held.
  • sync.RWMutex: Allows multiple concurrent reads while ensuring exclusive write access, improving performance when there are frequent read operations.

Is using RWMutex the best approach?

Let’s look at the following example.

Benchmark: Mutex & RWMutex

Example 1. Number of READERS ≤ Number of WRITERS

Let’s take a look at the following benchmark code:

This code tests the performance of Mutex Lock, RWMutex Lock, and RLock.

You can adjust the number of readers and writers.

package main

import (
"sync"
"testing"
)

const (
numReaders = 10
numWriters = 10
iterations = 1000
)

// BenchmarkMutex tests the performance of sync.Mutex
func BenchmarkMutex(b *testing.B) {
for i := 0; i < b.N; i++ {
var m sync.Mutex
var data int
var wg sync.WaitGroup

// Start writer goroutines
for i := 0; i < numWriters; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j…

--

--

No responses yet