-
Notifications
You must be signed in to change notification settings - Fork 0
/
locker.go
54 lines (41 loc) · 917 Bytes
/
locker.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
package middleware
import (
"context"
"github.com/D3rus/go-library/repeater"
"sync"
)
type lockTask struct {
repeater.Task
locked bool
rwMutex *sync.RWMutex
}
func newLockTask(task repeater.Task) *lockTask {
return &lockTask{Task: task, rwMutex: &sync.RWMutex{}}
}
func (task *lockTask) Process(ctx context.Context) error {
if task.lock() {
return nil
}
task.setLock(true)
defer task.setLock(false)
return task.Task.Process(ctx)
}
func (task *lockTask) lock() bool {
task.rwMutex.RLock()
defer task.rwMutex.RUnlock()
return task.locked
}
func (task *lockTask) setLock(locked bool) {
task.rwMutex.Lock()
defer task.rwMutex.Unlock()
task.locked = locked
}
func Locker() repeater.MiddlewareFunc {
manager := newTaskManager()
return func(next repeater.Task) repeater.Task {
if task, exist := manager.get(next); exist {
return task
}
return manager.add(newLockTask(next))
}
}