-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathasync.go
112 lines (90 loc) · 1.75 KB
/
async.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
package iot
import (
"sync"
"time"
)
type DeviceError struct {
errorMsg string
}
func (err *DeviceError) Error() string {
return err.errorMsg
}
type AsyncResult interface {
Wait() bool
WaitTimeout(time.Duration) bool
Done() <-chan struct{}
Error() error
}
type baseAsyncResult struct {
m sync.RWMutex
complete chan struct{}
err error
}
// Wait implements the Token Wait method.
func (b *baseAsyncResult) Wait() bool {
<-b.complete
return true
}
// WaitTimeout implements the Token WaitTimeout method.
func (b *baseAsyncResult) WaitTimeout(d time.Duration) bool {
timer := time.NewTimer(d)
select {
case <-b.complete:
if !timer.Stop() {
<-timer.C
}
return true
case <-timer.C:
}
return false
}
// Done implements the Token Done method.
func (b *baseAsyncResult) Done() <-chan struct{} {
return b.complete
}
func (b *baseAsyncResult) flowComplete() {
select {
case <-b.complete:
default:
close(b.complete)
}
}
func (b *baseAsyncResult) Error() error {
b.m.RLock()
defer b.m.RUnlock()
return b.err
}
func (b *baseAsyncResult) setError(e error) {
b.m.Lock()
b.err = e
b.flowComplete()
b.m.Unlock()
}
type BooleanAsyncResult struct {
baseAsyncResult
}
func (bar *BooleanAsyncResult) Result() bool {
bar.m.RLock()
defer bar.m.RUnlock()
return bar.err == nil
}
func (bar *BooleanAsyncResult) completeSuccess() {
bar.m.RLock()
defer bar.m.RUnlock()
bar.err = nil
bar.complete <- struct{}{}
}
func (bar *BooleanAsyncResult) completeError(err error) {
bar.m.RLock()
defer bar.m.RUnlock()
bar.err = err
bar.complete <- struct{}{}
}
func NewBooleanAsyncResult() *BooleanAsyncResult {
asyncResult := &BooleanAsyncResult{
baseAsyncResult: baseAsyncResult{
complete: make(chan struct{}),
},
}
return asyncResult
}