Compare commits
No commits in common. "23b2b783e747dbf0d4feb2576eee4328a212a9f8" and "0d72c8a0729178e11d43ea4875fecb26dd52b58b" have entirely different histories.
23b2b783e7
...
0d72c8a072
47
pkg/lock/lock.go
Normal file
47
pkg/lock/lock.go
Normal file
@ -0,0 +1,47 @@
|
||||
package lock
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
var _ Locker = (*locker)(nil)
|
||||
|
||||
type Locker interface {
|
||||
condition() bool
|
||||
Lock()
|
||||
Unlock()
|
||||
}
|
||||
|
||||
type locker struct {
|
||||
lock *sync.Mutex
|
||||
cond *sync.Cond
|
||||
v *atomic.Bool
|
||||
}
|
||||
|
||||
func NewLocker() Locker {
|
||||
lock := new(sync.Mutex)
|
||||
return &locker{
|
||||
lock: lock,
|
||||
cond: sync.NewCond(lock),
|
||||
v: new(atomic.Bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *locker) condition() bool {
|
||||
return l.v.Load()
|
||||
}
|
||||
|
||||
func (l *locker) Lock() {
|
||||
l.cond.L.Lock()
|
||||
for l.condition() {
|
||||
l.cond.Wait()
|
||||
}
|
||||
l.v.Store(true)
|
||||
}
|
||||
|
||||
func (l *locker) Unlock() {
|
||||
l.v.Store(false)
|
||||
l.cond.L.Unlock()
|
||||
l.cond.Signal()
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user