-
Notifications
You must be signed in to change notification settings - Fork 65
/
work_unit.go
77 lines (60 loc) · 1.95 KB
/
work_unit.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
package pool
import "sync/atomic"
// WorkUnit contains a single uint of works values
type WorkUnit interface {
// Wait blocks until WorkUnit has been processed or cancelled
Wait()
// Value returns the work units return value
Value() interface{}
// Error returns the Work Unit's error
Error() error
// Cancel cancels this specific unit of work, if not already committed
// to processing.
Cancel()
// IsCancelled returns if the Work Unit has been cancelled.
// NOTE: After Checking IsCancelled(), if it returns false the
// Work Unit can no longer be cancelled and will use your returned values.
IsCancelled() bool
}
var _ WorkUnit = new(workUnit)
// workUnit contains a single unit of works values
type workUnit struct {
value interface{}
err error
done chan struct{}
fn WorkFunc
cancelled atomic.Value
cancelling atomic.Value
writing atomic.Value
}
// Cancel cancels this specific unit of work, if not already committed to processing.
func (wu *workUnit) Cancel() {
wu.cancelWithError(&ErrCancelled{s: errCancelled})
}
func (wu *workUnit) cancelWithError(err error) {
wu.cancelling.Store(struct{}{})
if wu.writing.Load() == nil && wu.cancelled.Load() == nil {
wu.cancelled.Store(struct{}{})
wu.err = err
close(wu.done)
}
}
// Wait blocks until WorkUnit has been processed or cancelled
func (wu *workUnit) Wait() {
<-wu.done
}
// Value returns the work units return value
func (wu *workUnit) Value() interface{} {
return wu.value
}
// Error returns the Work Unit's error
func (wu *workUnit) Error() error {
return wu.err
}
// IsCancelled returns if the Work Unit has been cancelled.
// NOTE: After Checking IsCancelled(), if it returns false the
// Work Unit can no longer be cancelled and will use your returned values.
func (wu *workUnit) IsCancelled() bool {
wu.writing.Store(struct{}{}) // ensure that after this check we are committed as cannot be cancelled if not aalready
return wu.cancelled.Load() != nil
}