-
Notifications
You must be signed in to change notification settings - Fork 0
/
util-mutex.go
127 lines (100 loc) · 2.26 KB
/
util-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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
* Copyright (c) 2023.
* Created by Andy Pangaribuan <https://github.com/apangaribuan>.
* All Rights Reserved.
*/
package util
import (
"context"
"fmt"
"math/rand"
"time"
"github.com/andypangaribuan/project9/abs"
"github.com/viney-shih/go-lock"
)
const min int64 = 10
const max int64 = 500
func (*srUtil) NewMutex(name string) abs.UtilMutex {
return &srMutex{
mux: lock.NewChanMutex(),
name: name,
}
}
func (slf *srMutex) Sleep(duration ...time.Duration) {
if len(duration) > 0 {
time.Sleep(duration[0])
} else {
x := rand.Int63n(max-min) + min
time.Sleep(time.Microsecond * time.Duration(x))
}
}
func (slf *srMutex) Unlock() {
slf.mux.Unlock()
}
func (slf *srMutex) Lock(timeout ...time.Duration) (isTimeout bool) {
if len(timeout) > 0 && timeout[0] > 0 {
ctx, cancel := context.WithTimeout(context.Background(), timeout[0])
defer cancel()
locked := slf.mux.TryLockWithContext(ctx)
if !locked {
isTimeout = true
}
return
}
slf.mux.Lock()
return
}
func (slf *srMutex) Exec(timeout *time.Duration, fn func()) (executed bool, panicErr error) {
var (
isUnlock = false
timeoutDuration = make([]time.Duration, 0)
)
if timeout != nil {
timeoutDuration = append(timeoutDuration, *timeout)
}
// log.Printf("u-mtx: %v", slf.name)
isTimeout := slf.Lock(timeoutDuration...)
if isTimeout {
return
}
defer func() {
if r := recover(); r != nil {
panicErr = fmt.Errorf("panic error: %+v", r)
}
if !isUnlock {
slf.Unlock()
}
}()
fn()
executed = true
slf.Unlock()
isUnlock = true
return
}
func (slf *srMutex) FExec(timeoutLock *time.Duration, timeoutFunc time.Duration, fn func()) (executed bool, isTimeout bool, panicErr error) {
executed, panicErr = slf.Exec(timeoutLock, func() {
isTimeout, panicErr = slf.Func(timeoutFunc, fn)
})
return
}
func (slf *srMutex) Func(timeout time.Duration, fn func()) (isTimeout bool, panicErr error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
go func(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
panicErr = fmt.Errorf("panic error: %+v", r)
}
cancel()
}()
fn()
}(ctx)
<-ctx.Done()
if panicErr != nil {
return
}
switch ctx.Err() {
case context.DeadlineExceeded:
isTimeout = true
}
return
}