-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspindle.go
87 lines (71 loc) · 1.75 KB
/
spindle.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package dlock
import (
"context"
"log"
"sync/atomic"
"time"
"cloud.google.com/go/spanner"
"github.com/flowerinthenight/spindle"
)
type SpindleLockOptions struct {
Client *spanner.Client // Spanner client
Table string // Spanner table name
Name string // lock name
Id string // optional, generated if empty
Duration int64 // optional, will use spindle's default
Logger *log.Logger // pass to spindle
}
func NewSpindleLock(opts *SpindleLockOptions) *SpindleLock {
if opts == nil {
return nil
}
s := &SpindleLock{opts: opts}
sopts := []spindle.Option{}
if opts.Id != "" {
sopts = append(sopts, spindle.WithId(opts.Id))
}
if opts.Duration != 0 {
sopts = append(sopts, spindle.WithDuration(opts.Duration))
}
if opts.Logger != nil {
sopts = append(sopts, spindle.WithLogger(opts.Logger))
}
s.lock = spindle.New(opts.Client, opts.Table, opts.Name, sopts...)
return s
}
type SpindleLock struct {
opts *SpindleLockOptions
lock *spindle.Lock
quit context.Context
cancel context.CancelFunc
locked int32
done chan error
}
func (l *SpindleLock) Lock(ctx context.Context) error {
if atomic.LoadInt32(&l.locked) == 1 {
// Lock only once for this instance.
return nil
}
l.quit, l.cancel = context.WithCancel(ctx)
l.done = make(chan error, 1)
l.lock.Run(l.quit, l.done)
// Block until we get the lock.
for {
hl, _ := l.lock.HasLock()
if l.lock.Iterations() > 1 && hl {
break
}
time.Sleep(time.Millisecond * 500)
}
atomic.StoreInt32(&l.locked, 1)
return nil
}
func (l *SpindleLock) Unlock() error {
if atomic.LoadInt32(&l.locked) != 1 {
return nil
}
l.cancel() // terminate lock loop
<-l.done // and wait
atomic.StoreInt32(&l.locked, 0)
return nil
}