Go course

Mutexessync.Mutex: Lock and Unlock

Go

Display

Theme

Mutexes · Test exercise

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:

  1. Lock l.mu at the start of the method and use defer to unlock it.
  2. 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.

main.go
package main

import (
	"fmt"
	"runtime"
	"sync"
)

type Loket struct {
	mu       sync.Mutex
	terakhir int
}

// Ambil mengembalikan nomor antrean berikutnya.
func (l *Loket) Ambil() int {
	// TODO: kunci l.mu dan buka kembali dengan defer
	nomor := l.terakhir + 1
	runtime.Gosched() // mesin sedang mencetak tiket...
	l.terakhir = nomor
	return nomor
}

func main() {
	loket := &Loket{}
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			loket.Ambil()
		}()
	}
	wg.Wait()
	fmt.Println("Nomor terakhir:", loket.terakhir)
}

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)