Protecting Structs with a Mutex
The most common pattern in Go: put the mutex inside the struct whose data it protects, then make sure every method that reads or writes that data takes the lock.
type Inventori struct {
mu sync.Mutex // melindungi field di bawahnya
stok int
}
func (inv *Inventori) Stok() int {
inv.mu.Lock()
defer inv.mu.Unlock()
return inv.stok
}
By convention, the mutex field goes above the fields it guards, often with a comment like the one above.
Reading needs the lock too
It may feel odd, but methods that only read must lock as well. Without the lock, a reader can see data that another goroutine is halfway through updating.
Check-then-modify must be atomic
A classic mistake is checking a condition and changing the data in two separate steps:
// SALAH: dua goroutine bisa sama-sama lolos pemeriksaan
if inv.Stok() >= jumlah { // kunci diambil lalu dilepas
inv.kurangi(jumlah) // kunci diambil lagi — terlambat!
}
Another goroutine can sneak in between the check and the decrement. The check and the change have to live inside one critical section.
Named field vs embedded
You can also embed the mutex:
type Inventori struct {
sync.Mutex
stok int
}
inv.Lock() // method Lock "naik" ke Inventori
It's concise, but Lock and Unlock become part of your type's public API, so code outside the package can lock and unlock it however it likes. That's why an unexported field named mu is usually preferred.
Task
Build a digital wallet that's safe to use from many goroutines. The Dompet struct and the ErrSaldoKurang error are already provided. Complete three methods:
func (d *Dompet) Setor(jumlah int)adds to the balance.func (d *Dompet) Tarik(jumlah int) error: ifjumlahis larger than the balance, returnErrSaldoKurangand don't change the balance. If there's enough, subtract from the balance and returnnil.func (d *Dompet) Saldo() intreturns the current balance.
All three must lock d.mu (use defer). Make sure the balance check and the subtraction in Tarik happen under the same lock.