forked from lavanet/lava
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locks.go
105 lines (91 loc) · 1.84 KB
/
locks.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package utils
import (
"fmt"
"runtime"
"strconv"
"sync"
"time"
)
const TIMEOUT = 10
var (
TimeoutMutex = "false"
TimeoutMutexBoolean, _ = strconv.ParseBool(TimeoutMutex)
)
type Lockable interface {
Lock()
TryLock() bool
Unlock()
}
type LavaMutex struct {
mu sync.Mutex
quit chan bool
SecondsLeft int
lineAndFile string
lockCount int
}
func (dm *LavaMutex) getLineAndFile() string {
_, file, line, _ := runtime.Caller(2)
return fmt.Sprintf("%s:%d", file, line)
}
func (dm *LavaMutex) waitForTimeout() {
dm.quit = make(chan bool)
ticker := time.NewTicker(TIMEOUT * time.Second)
go func() {
for {
select {
case <-dm.quit:
ticker.Stop()
return
case <-ticker.C:
ticker.Stop()
fmt.Printf("WARNING: Mutex is Locked for more than %d seconds \n %s \n", TIMEOUT, dm.lineAndFile)
return
}
}
}()
}
func (dm *LavaMutex) Lock() {
if TimeoutMutexBoolean {
tempLineAndFile := dm.getLineAndFile()
dm.lockCount++
fmt.Printf("Lock: %s, count %d ... ", tempLineAndFile, dm.lockCount)
dm.mu.Lock()
fmt.Printf("locked \n")
dm.lineAndFile = tempLineAndFile
dm.SecondsLeft = TIMEOUT
dm.waitForTimeout()
} else {
dm.mu.Lock()
}
}
func (dm *LavaMutex) TryLock() (isLocked bool) {
if TimeoutMutexBoolean {
tempLineAndFile := dm.getLineAndFile()
isLocked = dm.mu.TryLock()
if isLocked {
dm.lockCount++
// fmt.Println("TryLock Locked: ", tempLineAndFile)
dm.lineAndFile = tempLineAndFile
dm.SecondsLeft = TIMEOUT
dm.waitForTimeout()
}
return isLocked
} else {
return dm.mu.TryLock()
}
}
func (dm *LavaMutex) Unlock() {
if TimeoutMutexBoolean {
// fmt.Println("Unlock: ", dm.getLineAndFile())
dm.lockCount++
dm.quit <- true
}
dm.mu.Unlock()
}
// func main() {
// x := LavaMutex{}
// x.Lock()
// time.Sleep(6 * time.Second)
// x.Unlock()
// return
// }