Section 9/101 menit

9. Mutex vs Atomic vs Actor — Kapan Memilih

9. Mutex vs Atomic vs Actor — Kapan Memilih

swift
State-mu berupa primitif tunggal (Int, Bool, pointer)?
├── YA → Atomic<Value>
│         Keuntungan: lock-free, sangat cepat
│         Contoh: counter, flag, reference count
└── TIDAK

State-mu kompleks (struct, multiple fields) atau logika non-trivial?
├── Semua akses dari async context (await tersedia)?
│   ├── YA → Actor
│   │         Keuntungan: natural Swift concurrency, cancellation support
│   │         Contoh: service layers, data stores dalam app
│   └── TIDAK (sync callback, init, atau perlu non-blocking)
│       └── Mutex<Value>
│             Keuntungan: synchronous, tidak butuh await, withLockIfAvailable
│             Contoh: delegate callbacks, plugin registry, metrics

Perbandingan Performa (Approximasi)

Primitive Overhead Thread Block? Async?
Atomic ~1-5 ns Tidak Tidak
Mutex.withLock ~10-50 ns Ya (OS lock) Tidak
actor hop ~100-500 ns Tidak (suspend) Ya (butuh await)
DispatchQueue.sync ~500-2000 ns Ya Tidak

Angka sangat bervariasi tergantung contention dan hardware.