-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlock.go
More file actions
68 lines (60 loc) · 1.55 KB
/
lock.go
File metadata and controls
68 lines (60 loc) · 1.55 KB
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
package gomysqllock
import (
"context"
"database/sql"
"errors"
"sync"
"time"
)
var (
ErrLockReleased = errors.New("Lock already released")
)
// Lock denotes an acquired lock and presents two methods, one for getting the context which is cancelled when the lock
// is lost/released and other for Releasing the lock
type Lock struct {
key string
conn *sql.Conn
unlocker chan (struct{})
lostLockContext context.Context
cancelFunc context.CancelFunc
released bool
mx sync.Mutex
}
// GetContext returns a context which is cancelled when the lock is lost or released
func (l *Lock) GetContext() context.Context {
return l.lostLockContext
}
// Release unlocks the lock
func (l *Lock) Release() error {
l.mx.Lock()
defer l.mx.Unlock()
if !l.released {
l.released = true
l.unlocker <- struct{}{}
l.conn.ExecContext(context.Background(), "DO RELEASE_LOCK(?)", l.key)
return l.conn.Close()
}
return ErrLockReleased
}
func (l *Lock) refresher(duration time.Duration, cancelFunc context.CancelFunc) {
for {
select {
case <-time.After(duration):
deadline := time.Now().Add(duration)
contextDeadline, deadlineCancelFunc := context.WithDeadline(context.Background(), deadline)
// try refresh, else cancel
err := l.conn.PingContext(contextDeadline)
if err != nil {
cancelFunc()
deadlineCancelFunc()
// this will make sure connection is closed
l.Release()
return
}
deadlineCancelFunc() // to avoid context leak
case <-l.unlocker:
cancelFunc()
return
}
}
}