mirror of
https://github.com/datarhei/core.git
synced 2025-10-23 07:59:26 +08:00
Split Lock type into its own file
This commit is contained in:
@@ -1,8 +1,6 @@
|
||||
package kvs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/datarhei/core/v16/cluster/store"
|
||||
@@ -18,41 +16,3 @@ type KVS interface {
|
||||
GetKV(key string) (string, time.Time, error)
|
||||
ListKV(prefix string) map[string]store.Value
|
||||
}
|
||||
|
||||
type Lock struct {
|
||||
ValidUntil time.Time
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func (l *Lock) Expired() <-chan struct{} {
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
|
||||
if l.ctx == nil {
|
||||
l.ctx, l.cancel = context.WithDeadline(context.Background(), l.ValidUntil)
|
||||
|
||||
go func(l *Lock) {
|
||||
<-l.ctx.Done()
|
||||
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
if l.cancel != nil {
|
||||
l.cancel()
|
||||
}
|
||||
}(l)
|
||||
}
|
||||
|
||||
return l.ctx.Done()
|
||||
}
|
||||
|
||||
func (l *Lock) Unlock() {
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
|
||||
if l.cancel != nil {
|
||||
l.ValidUntil = time.Now()
|
||||
l.cancel()
|
||||
}
|
||||
}
|
||||
|
45
cluster/kvs/lock.go
Normal file
45
cluster/kvs/lock.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package kvs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Lock struct {
|
||||
ValidUntil time.Time
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func (l *Lock) Expired() <-chan struct{} {
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
|
||||
if l.ctx == nil {
|
||||
l.ctx, l.cancel = context.WithDeadline(context.Background(), l.ValidUntil)
|
||||
|
||||
go func(l *Lock) {
|
||||
<-l.ctx.Done()
|
||||
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
if l.cancel != nil {
|
||||
l.cancel()
|
||||
}
|
||||
}(l)
|
||||
}
|
||||
|
||||
return l.ctx.Done()
|
||||
}
|
||||
|
||||
func (l *Lock) Unlock() {
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
|
||||
if l.cancel != nil {
|
||||
l.ValidUntil = time.Now()
|
||||
l.cancel()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user