-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathlockgate.go
50 lines (42 loc) · 1.28 KB
/
lockgate.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
package lockgate
import "time"
// Locker is an abstract interface to interact with the locker.
// Locker implementation is always thread safe so it is possible
// to use a single Locker in multiple goroutines.
//
// Note that LockHandle objects should be managed by the user manually to
// acquire multiple locks from the same process: to release a lock user must pass
// the same LockHandle object that was given by Acquire method to the Release method.
type Locker interface {
Acquire(lockName string, opts AcquireOptions) (bool, LockHandle, error)
Release(lock LockHandle) error
}
type LockHandle struct {
UUID string `json:"uuid"`
LockName string `json:"lockName"`
}
type AcquireOptions struct {
NonBlocking bool
Timeout time.Duration
Shared bool
AcquirerId string
OnWaitFunc func(lockName string, doWait func() error) error
OnLostLeaseFunc func(lock LockHandle) error
}
func WithAcquire(locker Locker, lockName string, opts AcquireOptions, f func(acquired bool) error) (resErr error) {
if acquired, lock, err := locker.Acquire(lockName, opts); err != nil {
return err
} else {
if acquired {
defer func() {
if err := locker.Release(lock); err != nil {
if resErr == nil {
resErr = err
}
}
}()
}
resErr = f(acquired)
}
return
}