Middle
What needs to be done to write your own Mutex? What is Compare-And-Swap?
sobes.tech AI
Answer from AI
To write your own Mutex (mutual exclusion) in Go, you need to implement a mechanism that guarantees that only one goroutine can access the critical section at a time.
Main steps:
- Use atomic operations to check and set the lock state.
- If the lock is busy, the goroutine should wait (for example, via a spin loop with sleep or a channel).
Compare-And-Swap (CAS) is an atomic operation that compares the value at an address with an expected value and, if they match, replaces it with a new value. It returns whether the replacement was successful.
CAS allows implementing lock-free data structures and synchronization without heavy primitives.
Example of a simplified Mutex based on CAS:
import (
"sync/atomic"
"runtime"
)
type Mutex struct {
state int32
}
func (m *Mutex) Lock() {
for !atomic.CompareAndSwapInt32(&m.state, 0, 1) {
runtime.Gosched() // yield to the scheduler
}
}
func (m *Mutex) Unlock() {
atomic.StoreInt32(&m.state, 0)
}
Here, state is 0 when the mutex is free, and 1 when it is locked. The Lock method tries to set state to 1 if it was 0, using CAS. If it fails, the goroutine yields to the scheduler and retries.