forked from tehsphinx/concurrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cancel_context.go
64 lines (53 loc) · 1.46 KB
/
cancel_context.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
package concurrent
import (
"context"
"sync"
"time"
)
// NewCancelContext creates a new cancel context from given context
// and wraps it in the concurrency save struct CancelContext.
//
// Note: this context does not implement the context.Context interface
// because contexts derived from it would still be done if this context
// gets resetted.
func NewCancelContext(ctx context.Context) *CancelContext {
s := &CancelContext{}
s.Reset(ctx)
return s
}
// CancelContext implements a context with cancelation that can be used from multiple goroutines.
type CancelContext struct {
ctxCancel context.Context
cancel context.CancelFunc
m sync.RWMutex
}
// Cancel cancels the context.
func (s *CancelContext) Cancel() {
s.m.RLock()
s.cancel()
s.m.RUnlock()
}
// Done returns the Done channel of the cancel context.
func (s *CancelContext) Done() <-chan struct{} {
s.m.RLock()
defer s.m.RUnlock()
return s.ctxCancel.Done()
}
// Reset creates a new cancel context from the given context, thereby resetting a cancelled context.
func (s *CancelContext) Reset(ctx context.Context) {
s.m.Lock()
s.ctxCancel, s.cancel = context.WithCancel(ctx)
s.m.Unlock()
}
// Deadline implements context.Context
func (s *CancelContext) Deadline() (deadline time.Time, ok bool) {
s.m.RLock()
defer s.m.RUnlock()
return s.ctxCancel.Deadline()
}
// Err implements context.Context
func (s *CancelContext) Err() error {
s.m.RLock()
defer s.m.RUnlock()
return s.ctxCancel.Err()
}