github.com/haraldrudell/parl@v0.4.176/mutex-wait.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package parl 7 8 import ( 9 "sync" 10 "sync/atomic" 11 ) 12 13 // MutexWait is maximum-lightweight observable single-fire Mutex. Thread-Safe 14 type MutexWait struct { 15 lock sync.Mutex 16 isUnlocked atomic.Bool 17 } 18 19 // NewMutexWait returns a maximum-lightweight observable single-fire Mutex. Thread-Safe 20 func NewMutexWait() (mutexWait *MutexWait) { 21 mutexWait = &MutexWait{} 22 mutexWait.lock.Lock() 23 return 24 } 25 26 // IsUnlocked returns whether the MutexWait has fired 27 func (mw *MutexWait) IsUnlocked() (isUnlocked bool) { 28 return mw.isUnlocked.Load() 29 } 30 31 // Wait blocks until MutexWait has fired 32 func (mw *MutexWait) Wait() { 33 mw.lock.Lock() 34 defer mw.lock.Unlock() 35 } 36 37 // Unlock fires MutexWait 38 func (mw *MutexWait) Unlock() { 39 if mw.isUnlocked.CompareAndSwap(false, true) { 40 mw.lock.Unlock() 41 } 42 }