-
Notifications
You must be signed in to change notification settings - Fork 240
/
filemu.go
48 lines (37 loc) · 1.09 KB
/
filemu.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
// Package filemu implements file-based mutexes.
package filemu
import (
"context"
"errors"
"time"
"github.com/gofrs/flock"
)
// UnlockFunc is the set of unlock functions.
type UnlockFunc func() error
const (
timeout = time.Second
retryDelay = timeout / 10
)
// Lock attempts to acquire an exclusive lock on the named file.
func Lock(ctx context.Context, path string) (UnlockFunc, error) {
return try(ctx, path, (*flock.Flock).TryLockContext)
}
// RLock attempts to acquire a shared lock on the named file.
func RLock(ctx context.Context, path string) (UnlockFunc, error) {
return try(ctx, path, (*flock.Flock).TryRLockContext)
}
var errFailed = errors.New("failed acquiring lock")
type lockFunc func(*flock.Flock, context.Context, time.Duration) (bool, error)
func try(parent context.Context, path string, fn lockFunc) (UnlockFunc, error) {
ctx, cancel := context.WithTimeout(parent, timeout)
defer cancel()
mu := flock.New(path)
switch locked, err := fn(mu, ctx, retryDelay); {
case err != nil:
return nil, err
case !locked:
return nil, errFailed
default:
return mu.Unlock, nil
}
}