-
Notifications
You must be signed in to change notification settings - Fork 1
/
mutex.go
79 lines (68 loc) · 1.52 KB
/
mutex.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
package astiredis
import (
"time"
"context"
"github.com/asticode/go-astitools/time"
"github.com/pkg/errors"
)
// Mutex represents a distributed mutex
type Mutex struct {
c *Client
ctx context.Context
key string
sleep time.Duration
timeout time.Duration
}
// MutexOptions represents mutex options
type MutexOptions struct {
Key string
Sleep time.Duration
Timeout time.Duration
}
// NewMutex creates a new mutex
func (c *Client) NewMutex(ctx context.Context) *Mutex {
return c.NewMutexWithOptions(ctx, MutexOptions{
Key: "distributed.mutex",
Sleep: 500 * time.Millisecond,
})
}
// NewMutexWithOptions creates a new mutex with options
func (c *Client) NewMutexWithOptions(ctx context.Context, o MutexOptions) *Mutex {
return &Mutex{
c: c,
ctx: ctx,
key: o.Key,
sleep: o.Sleep,
timeout: o.Timeout,
}
}
// Lock lock the mutex
func (l *Mutex) Lock() (err error) {
for {
// Check context error
if l.ctx.Err() != nil {
err = errors.Wrap(err, "astiredis: context error")
return
}
// Try to set the key
var ok bool
if ok, err = l.c.SetNX(l.key, true, l.timeout); err != nil {
err = errors.Wrapf(err, "astiredis: setting mutex key %s failed", l.key)
return
}
// Key already exists
if !ok {
astitime.Sleep(l.ctx, l.sleep)
continue
}
return
}
}
// Unlock unlocks the mutex
func (l *Mutex) Unlock() (err error) {
if err = l.c.Del(l.key); err != nil {
err = errors.Wrapf(err, "astiredis: deleting mutex key %s failed", l.key)
return
}
return
}