-
Notifications
You must be signed in to change notification settings - Fork 1
/
nb-chan.go
281 lines (236 loc) · 7.28 KB
/
nb-chan.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
© 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parl
import (
"sync"
"time"
"github.com/haraldrudell/parl/perrors"
"github.com/haraldrudell/parl/pruntime"
)
// NBChan is a non-blocking send channel with trillion-size buffer.
//
// - NBChan can be used as an error channel where the thread does not
// block from a delayed or missing reader.
// - errors can be read from the channel or fetched all at once using GetAll
// - NBChan is initialization-free, thread-safe, idempotent, deferrable and observable.
// - Ch(), Send(), Close() CloseNow() IsClosed() Count() are not blocked by channel send
// and are panic-free.
// - Close() CloseNow() are deferrable.
// - WaitForClose() waits until the underlying channel has been closed.
// - NBChan implements a thread-safe error store perrors.ParlError.
// - NBChan.GetError() returns thread panics and close errors.
// - No errors are added to the error store after the channel has closed.
// - NBChan does not generate errors. When it does, errors are thread panics
// or a close error. Neither is expected to occur
// - the underlying channel is closed after Close is invoked and the channel is emptied
// - cautious consumers may collect errors using the GetError method when:
// - — the Ch receive-only channel is detected as being closed or
// - — await using WaitForClose returns or
// - — IsClosed method returns true
//
// Usage:
//
// var errCh parl.NBChan[error]
// go thread(&errCh)
// err, ok := <-errCh.Ch()
// errCh.WaitForClose()
// errCh.GetError()
// …
// func thread(errCh *parl.NBChan[error]) {
// defer errCh.Close() // non-blocking close effective on send complete
// var err error
// defer parl.Recover(parl.Annotation(), &err, errCh.AddErrorProc)
// errCh.Ch() <- err // non-blocking
// if err = someFunc(); err != nil {
// err = perrors.Errorf("someFunc: %w", err)
// return
type NBChan[T any] struct {
closableChan ClosableChan[T]
pendingSend AtomicBool
stateLock sync.Mutex
unsentCount int // inside lock
sendQueue []T // inside lock
waitForCloseInitialized bool // inside lock
closeInvoked AtomicBool
waitForClose sync.WaitGroup // initialization inside lock
waitForThread WaitGroup // observable waitgroup
perrors.ParlError // thread panics
}
// NewNBChan instantiates a non-blocking trillion-size buffer channel.
// NewNBChan allows initialization based on an existing channel.
// NewNBChan does not need initialization and can be used like:
//
// var nbChan NBChan[error]
// go thread(&nbChan)
func NewNBChan[T any](ch ...chan T) (nbChan *NBChan[T]) {
nb := NBChan[T]{}
nb.closableChan = *NewClosableChan(ch...) // store ch if present
return &nb
}
// Ch obtains the receive-only channel
func (nb *NBChan[T]) Ch() (ch <-chan T) {
return nb.closableChan.Ch()
}
// Send sends non-blocking on the channel
func (nb *NBChan[T]) Send(value T) {
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
if nb.closeInvoked.IsTrue() {
return // no send after Close()
}
nb.unsentCount++
// if no thread, send using new thread
if nb.waitForThread.IsZero() {
nb.pendingSend.Set()
nb.waitForThread.Add(1)
go nb.sendThread(value) // send err in new thread
return
}
// put in queue
nb.sendQueue = append(nb.sendQueue, value) // put err in send queue
}
// GetAll returns a slice of all available items held by the channel.
func (nb *NBChan[T]) GetAll() (allItems []T) {
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
// get possible item from send thread
var item T
var itemValid bool
for nb.pendingSend.IsTrue() && !itemValid {
select {
case item, itemValid = <-nb.closableChan.ch:
default:
time.Sleep(time.Millisecond)
}
}
// allocate and populate allItems
var itemLength int
if itemValid {
itemLength = 1
}
n := len(nb.sendQueue)
allItems = make([]T, n+itemLength)
if itemValid {
allItems[0] = item
}
// empty the send buffer
if n > 0 {
copy(allItems[itemLength:], nb.sendQueue)
nb.sendQueue = nb.sendQueue[:0]
nb.unsentCount -= n
}
return
}
// Count returns number of unsent values
func (nb *NBChan[T]) Count() (unsentCount int) {
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
return nb.unsentCount
}
// Close orders the channel to close once pending sends complete.
// Close is thread-safe, non-blocking and panic-free.
func (nb *NBChan[T]) Close() (didClose bool) {
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
if !nb.closeInvoked.Set() {
return // Close was already invoked
}
if !nb.waitForThread.IsZero() {
return // there is a pending thread that will execute close on exit
}
var err error
if didClose, err = nb.closableChan.Close(); didClose && err != nil { // execute the close now
nb.AddError(err) // store posible close error
}
return
}
func (nb *NBChan[T]) DidClose() (didClose bool) {
return nb.closeInvoked.IsTrue()
}
// IsClosed indicates whether the channel has actually closed.
func (nb *NBChan[T]) IsClosed() (isClosed bool) {
return nb.closableChan.IsClosed()
}
func (nb *NBChan[T]) WaitForClose() {
nb.initWaitForClose() // ensure waitForClose state is valid
nb.waitForClose.Wait()
}
// CloseNow closes without waiting for sends to complete.
// Close does not panic.
// Close is thread-safe.
// Close does not return until the channel is closed.
// Upon return, all invocations have a possible close error in err.
// if errp is non-nil, it is updated with error status
func (nb *NBChan[T]) CloseNow(errp ...*error) (err error, didClose bool) {
if nb.closableChan.IsClosed() {
return // channel is already closed
}
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
nb.closeInvoked.Set()
// discard pending data
if len(nb.sendQueue) > 0 {
nb.sendQueue = nil
nb.unsentCount = 0
}
// close the channel now
if didClose, err = nb.closableChan.Close(); didClose && err != nil { // execute the close now
nb.AddError(err) // store posible close error
}
return
}
func (nb *NBChan[T]) sendThread(value T) {
defer nb.sendThreadDefer()
defer Recover(Annotation(), nil, func(err error) {
if pruntime.IsSendOnClosedChannel(err) {
return // ignore if the channel was or became closed
}
nb.AddError(err)
})
defer nb.pendingSend.Clear()
ch := nb.closableChan.Ch()
for {
ch <- value // may block or panic
nb.pendingSend.Clear()
var ok bool
if value, ok = nb.valueToSend(); !ok {
break
}
}
}
func (nb *NBChan[T]) valueToSend() (value T, ok bool) {
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
// count the item ust sent
nb.unsentCount--
// no more values: end thread
if len(nb.sendQueue) == 0 {
return
}
// send next value in queue
value = nb.sendQueue[0]
ok = true
copy(nb.sendQueue[0:], nb.sendQueue[1:])
nb.sendQueue = nb.sendQueue[:len(nb.sendQueue)-1]
nb.pendingSend.Set()
return
}
func (nb *NBChan[T]) sendThreadDefer() {
if nb.closeInvoked.IsTrue() { // Close() was invoked after thread started
nb.closableChan.Close() // close if Close was invoked. Idempotent
}
nb.waitForThread.Done() // thread has exit
}
func (nb *NBChan[T]) initWaitForClose() {
nb.stateLock.Lock()
defer nb.stateLock.Unlock()
if nb.waitForCloseInitialized {
return // state is valid
}
nb.waitForCloseInitialized = true
if !nb.closableChan.IsClosed() {
nb.waitForClose.Add(1) // has to wait for close to occur
}
}