Go course

MutexesProtecting Structs with a Mutex

Go

Display

Theme

Mutexes · Test exercise

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: if jumlah is larger than the balance, return ErrSaldoKurang and don't change the balance. If there's enough, subtract from the balance and return nil.
  • func (d *Dompet) Saldo() int returns 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.

main.go
package main

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

var ErrSaldoKurang = errors.New("saldo tidak cukup")

type Dompet struct {
	mu    sync.Mutex // melindungi saldo
	saldo int
}

func (d *Dompet) Setor(jumlah int) {
	// TODO: lindungi dengan d.mu
	baru := d.saldo + jumlah
	runtime.Gosched()
	d.saldo = baru
}

func (d *Dompet) Tarik(jumlah int) error {
	// TODO: periksa saldo, kurangi, atau kembalikan ErrSaldoKurang
	return nil
}

func (d *Dompet) Saldo() int {
	// TODO: lindungi dengan d.mu
	return d.saldo
}

func main() {
	d := &Dompet{}
	d.Setor(50000)
	if err := d.Tarik(80000); err != nil {
		fmt.Println("Gagal tarik:", err)
	}
	fmt.Println("Saldo:", d.Saldo())
}

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)