-
Notifications
You must be signed in to change notification settings - Fork 0
/
stateful.go
77 lines (65 loc) · 1.48 KB
/
stateful.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package ctxroutines
import (
"sync"
)
// StatefulRunner represents a Runner that can inspect its running state
type StatefulRunner interface {
Runner
IsRunning() bool
// Try to run the Runner if it's not running. ran will be true if it runs.
TryRun() (err error, ran bool)
// Lock the runner, pretending that it's running. Call release() to unlock.
// It's safe to call release more than once.
//
// It will block until previous Run() has finished.
Lock() (release func())
}
type statefulRunner struct {
token chan bool
Runner
}
func (f *statefulRunner) IsRunning() (yes bool) {
select {
case <-f.token:
f.token <- true
return false
default:
return true
}
}
func (f *statefulRunner) TryRun() (err error, ran bool) {
select {
case <-f.token:
f.token <- true
return f.Run(), true
default:
return
}
}
func (f *statefulRunner) Run() (err error) {
<-f.token
err = f.Runner.Run()
f.token <- true
return
}
func (f *statefulRunner) Lock() (release func()) {
<-f.token
once := &sync.Once{}
return func() {
once.Do(func() {
f.token <- true
})
}
}
// NewStatefulRunner creates a StatefulRunner from existing Runner
func NewStatefulRunner(f Runner) (ret StatefulRunner) {
x := &statefulRunner{
token: make(chan bool, 1),
Runner: f,
}
x.token <- true
return x
}