CodeBlanks Logo Icon CodeBlanks

sync.RWMutex

Learn the read-write mutex and RLock/RUnlock.

sync.RWMutex

When reads are far more frequent than writes, use sync.RWMutex. Several readers can hold RLock at once; when a writer takes Lock, both readers and other writers wait.

type Onbellek struct {
    mu sync.RWMutex
    m  map[string]string
}

func (o *Onbellek) Al(k string) (string, bool) {
    o.mu.RLock()
    defer o.mu.RUnlock()
    v, ok := o.m[k]
    return v, ok
}

Maps and concurrency

Go maps aren't safe for concurrent writes; reading and writing at the same time crashes the program with fatal error: concurrent map read and map write. The options: protect the map with an RWMutex, or use sync.Map for many-goroutine cases where keys rarely change. In most cases an RWMutex is clearer and faster.

Practice Safe cache

Write the Onbellek type with sync.RWMutex and map[string]string. Koy(k, v string) uses Lock and Al(k string) string uses RLock. Put "dil" = "go", read it back and print it.

Starter code

main.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "sync"
)

type Onbellek struct {
    mu sync.RWMutex
    m  map[string]string
}

func (o *Onbellek) Koy(k, v string) {
    o.mu.Lock()
    defer o.mu.Unlock()
    if o.m == nil {
        o.m = map[string]string{}
    }
    o.m[k] = v
}

func (o *Onbellek) Al(k string) string {
    o.mu.RLock()
    defer o.mu.RUnlock()
    return o.m[k]
}

func main() {
    var o Onbellek
    o.Koy("dil", "go")
    fmt.Println(o.Al("dil"))
}

Expected output

go

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 While a goroutine waits for <code>Lock</code> to write, what happens to new <code>RLock</code> requests?

  • The Lock is cancelled
  • They wait, so the writer doesn't starve Correct answer
  • They are granted immediately
  • They panic

Explanation: Go's RWMutex holds back new readers when a writer is waiting; otherwise continuous reads would keep the writer waiting forever.

2 Read lock

Question
o.mu.____()
defer o.mu.RUnlock()
return o.m[k]
Answer
o.mu.RLock()
defer o.mu.RUnlock()
return o.m[k]

Explanation: RLock lets several readers enter at the same time.

3 Method and use

Term Meaning
RLock / RUnlock Reading
Lock / Unlock Writing
sync.Map Rarely changing keys
Unprotected map Crashes on concurrent writes

All lessons in Intermediate