-
Notifications
You must be signed in to change notification settings - Fork 4
/
action.go
57 lines (48 loc) · 1.02 KB
/
action.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
package gostratum
import(
"sync"
"time"
"errors"
)
type Action struct{
cond *sync.Cond
response *Response
active bool
timer *time.Timer
}
func MakeAction() *Action{
return &Action{
cond: &sync.Cond{L: &sync.Mutex{}},
response: nil,
active: true,
timer: nil};
}
func (a *Action) SetTimeout(timeout time.Duration, callback func()){
a.cond.L.Lock()
defer a.cond.L.Unlock()
if a.timer != nil {a.timer.Stop()}
if timeout != 0 {
a.timer = time.AfterFunc(timeout, func(){
callback()
a.Done(&Response{Error:errors.New("timeout")})
})
}else{
a.timer = nil
}
}
func (a *Action) Wait() *Response{
a.cond.L.Lock()
if a.active{
a.cond.Wait()
}
a.cond.L.Unlock()
return a.response
}
func (a *Action) Done(response *Response){
a.cond.L.Lock()
a.response = response
a.active = false
if a.timer != nil {a.timer.Stop()}
a.cond.L.Unlock()
a.cond.Signal()
}