Go course

Mutexessync.RWMutex: Many Readers, One Writer

Go

Display

Theme

Mutexes · Test exercise

sync.RWMutex: Many Readers, One Writer

A lot of data in real apps is read often but rarely changed, like the price list of an online store. With a plain sync.Mutex, even two readers have to take turns, even though reading at the same time is perfectly safe as long as nobody is writing.

sync.RWMutex has two kinds of lock:

MethodForBehavior
RLock / RUnlockreadingMany goroutines can hold the read lock at the same time.
Lock / UnlockwritingOnly one writer, and no readers while it holds the lock.
type Kurs struct {
	mu   sync.RWMutex
	nilai map[string]float64
}

func (k *Kurs) Ambil(kode string) float64 {
	k.mu.RLock()
	defer k.mu.RUnlock()
	return k.nilai[kode]
}

func (k *Kurs) Perbarui(kode string, v float64) {
	k.mu.Lock()
	defer k.mu.Unlock()
	k.nilai[kode] = v
}

Maps and goroutines

Maps in Go are not safe for concurrent use. If one goroutine writes to a map while another reads or writes it, the Go runtime stops the program with fatal error: concurrent map writes (or concurrent map read and map write). That's why a map shared between goroutines is almost always wrapped in a mutex.

When should you pick RWMutex?

  • Use RWMutex when reads far outnumber writes and the critical section isn't trivially short.
  • When in doubt, start with a plain sync.Mutex. RWMutex costs a bit more and isn't always faster.
  • Don't call Lock while still holding RLock in the same goroutine. That's a deadlock.

Task

Complete Katalog, an online store's product price list that thousands of visitors read and an admin updates now and then. The KatalogBaru constructor is already provided.

  • func (k *Katalog) SetHarga(nama string, harga int) stores or updates a price. Use the write lock.
  • func (k *Katalog) Harga(nama string) (int, bool) returns the price and true if the product exists, or 0, false if it doesn't. Use the read lock.
  • func (k *Katalog) Jumlah() int returns how many products are in the catalog. Use the read lock.

The tests run dozens of writers and hundreds of readers at the same time.

main.go
package main

import (
	"fmt"
	"sync"
)

type Katalog struct {
	mu    sync.RWMutex // melindungi harga
	harga map[string]int
}

func KatalogBaru() *Katalog {
	return &Katalog{harga: make(map[string]int)}
}

func (k *Katalog) SetHarga(nama string, harga int) {
	// TODO: kunci tulis, lalu simpan harga ke map
}

func (k *Katalog) Harga(nama string) (int, bool) {
	// TODO: kunci baca, lalu cari harga di map
	return 0, false
}

func (k *Katalog) Jumlah() int {
	// TODO: kunci baca, lalu kembalikan banyaknya produk
	return 0
}

func main() {
	k := KatalogBaru()
	k.SetHarga("kaos polos", 75000)
	k.SetHarga("topi", 45000)

	if h, ok := k.Harga("topi"); ok {
		fmt.Println("Harga topi:", h)
	}
	fmt.Println("Jumlah produk:", k.Jumlah())
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)