sync.Mutex: Lock and Unlock
The sync.Mutex type has two main methods:
Lock()takes the lock. If another goroutine is holding it, the caller waits until it's released.Unlock()releases the lock.
The zero value of sync.Mutex is ready to use, no initialization needed:
type Papan struct {
mu sync.Mutex
skor int
}
func (p *Papan) Tambah(poin int) {
p.mu.Lock()
p.skor += poin
p.mu.Unlock()
}
Use defer to Unlock
Forgetting to call Unlock (for example because of an early return) leaves other goroutines waiting forever, and the program deadlocks. The idiomatic Go pattern is to write defer right after Lock:
func (p *Papan) TambahJikaPositif(poin int) bool {
p.mu.Lock()
defer p.mu.Unlock() // pasti dijalankan saat fungsi selesai
if poin <= 0 {
return false // aman, Unlock tetap terpanggil
}
p.skor += poin
return true
}
The receiver must be a pointer
A mutex must not be copied once it's been used. If a method has a value receiver (func (p Papan) ...), every call works on a copy of the struct, mutex included, so the lock protects nothing. Always use a pointer receiver (*Papan) for types that contain a mutex. go vet will warn you if you accidentally copy a mutex.
Task
A clinic uses a digital queue ticket machine. Lots of patients press the button at the same time, and each one must get a unique number, in sequence starting from 1.
Complete the func (l *Loket) Ambil() int method in the editor:
- Lock
l.muat the start of the method and usedeferto unlock it. - Keep the existing read–
runtime.Gosched()–write logic; the method must return the number that was just taken.
The tests call Ambil from 1000 goroutines at once and check that no number is handed out twice and that terakhir ends up at 1000.