github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/sync2/mutex.go (about) 1 package sync2 2 3 import ( 4 "sync" 5 "sync/atomic" 6 7 "github.com/egonelbre/exp/sync2/runtime2" 8 ) 9 10 type Mutex struct { 11 mu sync.Mutex 12 owner int64 13 } 14 15 func (mu *Mutex) Lock() { 16 mu.mu.Lock() 17 atomic.StoreInt64(&mu.owner, runtime2.GOID()) 18 } 19 20 func (mu *Mutex) Unlock() { 21 owner := mu.owner 22 mu.mu.Unlock() 23 atomic.CompareAndSwapInt64(&mu.owner, owner, 0) 24 } 25 26 func (mu *Mutex) Own() bool { 27 return atomic.LoadInt64(&mu.owner) == runtime2.GOID() 28 } 29 30 func (mu *Mutex) MustOwn() { 31 owner := atomic.LoadInt64(&mu.owner) 32 if owner != runtime2.GOID() { 33 if owner == 0 { 34 panic("mutex was not locked") 35 } else { 36 panic("owner was different") 37 } 38 } 39 }