~/Using RWMutex in Golang for Concurrent Read Write

Mar 10, 2021


Use RWMutex in Golang to manage concurrent access. RWMutex allows multiple readers but only one writer, boosting performance for situations with more reads than writes. It is part of the sync package.

To use:

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import (
    "sync"
)

var rw sync.RWMutex
var value int

func read() int {
    rw.RLock()
    defer rw.RUnlock()
    return value
}

func write(val int) {
    rw.Lock()
    value = val
    rw.Unlock()
}

Key details:

For more, read official RWMutex docs.

Tags: [golang]