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