-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathqueue.go
More file actions
644 lines (571 loc) · 14 KB
/
queue.go
File metadata and controls
644 lines (571 loc) · 14 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
package executor
import (
"context"
"errors"
"math"
"sync"
"sync/atomic"
"time"
)
func NewLinkedQueue[T any](capacity int) Queue[T] {
if capacity < 0 {
capacity = 0
}
queue := &LinkedQueue[T]{
capacity: capacity,
}
return queue
}
func newLockQueue[T any](q Queue[T]) Queue[T] {
return &LockQueue[T]{
queue: q,
}
}
func NewLinkedBlockingRunnableQueue(capacity int) BlockingQueue[Runnable] {
return NewLinkedBlockingQueue[Runnable](capacity)
}
func NewLinkedBlockingQueue[T any](capacity int) BlockingQueue[T] {
if capacity <= 0 {
capacity = 0
}
return &LinkedBlockingQueue[T]{
likedQueue: &LinkedQueue[T]{capacity: capacity},
ctxLikedQueue: &LinkedQueue[*contextInfo]{capacity: math.MaxInt},
}
}
func NewChanBlockingRunnableQueue(capacity int) BlockingQueue[Runnable] {
return NewChanBlockingQueue[Runnable](capacity)
}
func NewChanBlockingQueue[T any](capacity int) BlockingQueue[T] {
if capacity <= 0 {
capacity = 0
}
return &ChanBlockingQueue[T]{
capacity: capacity,
ch: make(chan T, capacity),
}
}
type ChanBlockingQueue[T any] struct {
capacity int
ch chan T
mux sync.Mutex
ctxInfoMap sync.Map
}
func (c *ChanBlockingQueue[T]) Close() {
close(c.ch)
}
func (c *ChanBlockingQueue[T]) IsEmpty() bool {
return len(c.ch) == 0
}
func (c *ChanBlockingQueue[T]) IsFull() bool {
return len(c.ch) == c.capacity
}
func (c *ChanBlockingQueue[T]) Size() int {
return len(c.ch)
}
func (c *ChanBlockingQueue[T]) Capacity() int {
return c.capacity
}
func (c *ChanBlockingQueue[T]) Enqueue(item T) bool {
//不支持
return false
}
func (c *ChanBlockingQueue[T]) Dequeue() (T, bool) {
//不支持
var t T
return t, false
}
func (c *ChanBlockingQueue[T]) RemoveAll() []T {
result := make([]T, 0, len(c.ch))
for {
select {
case item, ok := <-c.ch:
if !ok {
return result
} else {
result = append(result, item)
}
default:
return result
}
}
}
func (c *ChanBlockingQueue[T]) Refresh(newCapacity int) bool {
return false
}
func (c *ChanBlockingQueue[T]) Put(item T) bool {
return c.Offer(item, maxTimeDuration)
}
func (c *ChanBlockingQueue[T]) Offer(item T, timeout time.Duration) bool {
ok := false
if timeout <= 0 {
select {
case c.ch <- item:
ok = true
default:
}
} else {
goroutineId := GetGoroutineID()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
ctxInfo := &contextInfo{ctx: ctx, cancel: cancel}
c.ctxInfoMap.Store(goroutineId, ctxInfo)
select {
case c.ch <- item:
ok = true
case <-ctx.Done():
}
cancel()
c.ctxInfoMap.Delete(goroutineId)
}
return ok
}
func (c *ChanBlockingQueue[T]) Take() (T, bool) {
return c.Poll(maxTimeDuration)
}
func (c *ChanBlockingQueue[T]) Poll(timeout time.Duration) (T, bool) {
ok := false
var item T
if timeout <= 0 {
select {
case item = <-c.ch:
ok = true
default:
}
} else {
goroutineId := GetGoroutineID()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
ctxInfo := &contextInfo{ctx: ctx, cancel: cancel}
c.ctxInfoMap.Store(goroutineId, ctxInfo)
select {
case item = <-c.ch:
ok = true
case <-ctx.Done():
}
cancel()
c.ctxInfoMap.Delete(goroutineId)
}
return item, ok
}
// Interrupt 极端情况下,对于切片的打断,返回值结果并不准确
func (c *ChanBlockingQueue[T]) Interrupt(goroutineId int64) {
ctxInfoAny, ok := c.ctxInfoMap.LoadAndDelete(goroutineId)
if ok {
ctxInfo := ctxInfoAny.(*contextInfo)
ctxInfo.cancel()
}
}
const itemKey = ""
const interruptKey = " "
type LinkedBlockingQueue[T any] struct {
mux sync.Mutex
likedQueue *LinkedQueue[T]
ctxLikedQueue *LinkedQueue[*contextInfo]
}
func (l *LinkedBlockingQueue[T]) IsEmpty() bool {
l.mux.Lock()
defer l.mux.Unlock()
return l.likedQueue.IsEmpty()
}
func (l *LinkedBlockingQueue[T]) IsFull() bool {
l.mux.Lock()
defer l.mux.Unlock()
return l.likedQueue.IsFull()
}
func (l *LinkedBlockingQueue[T]) Size() int {
l.mux.Lock()
defer l.mux.Unlock()
return l.likedQueue.Size()
}
func (l *LinkedBlockingQueue[T]) Capacity() int {
l.mux.Lock()
defer l.mux.Unlock()
return l.likedQueue.Capacity()
}
func (l *LinkedBlockingQueue[T]) Interrupt(goroutineId int64) {
l.mux.Lock()
defer l.mux.Unlock()
ctxInfo, ok := l.ctxLikedQueue.delete(goroutineId, func(ctxInfoItem *contextInfo, goroutineId any) bool {
return ctxInfoItem.goroutineId == goroutineId.(int64)
})
if ok {
interruptPtr := ctxInfo.ctx.Value(interruptKey).(*atomic.Bool)
interruptPtr.Store(true)
ctxInfo.cancel()
}
}
func (l *LinkedBlockingQueue[T]) Enqueue(item T) bool {
return l.likedQueue.Enqueue(item)
}
func (l *LinkedBlockingQueue[T]) Dequeue() (T, bool) {
return l.likedQueue.Dequeue()
}
func (l *LinkedBlockingQueue[T]) RemoveAll() []T {
l.mux.Lock()
defer l.mux.Unlock()
result := make([]T, 0, l.likedQueue.size+l.ctxLikedQueue.Size())
if l.likedQueue.IsFull() {
//如果满了,取完后,再唤醒阻塞的且获取
result = append(result, l.likedQueue.RemoveAll()...)
for {
blockCtxInfo, ok := l.ctxLikedQueue.Dequeue()
if ok {
//如果存在阻塞的协程,则唤醒,把添加的元素放进队列
itemPtr := blockCtxInfo.ctx.Value(itemKey).(*atomic.Pointer[T])
item := *itemPtr.Load()
blockCtxInfo.cancel()
//是没有被打断则被取消的才放入队列中
interruptPtr := blockCtxInfo.ctx.Value(interruptKey).(*atomic.Bool)
if errors.Is(blockCtxInfo.ctx.Err(), context.Canceled) && !interruptPtr.Load() {
result = append(result, item)
}
} else {
break
}
}
} else {
//如果没有满,则直接返回
result = append(result, l.likedQueue.RemoveAll()...)
}
return result
}
func (l *LinkedBlockingQueue[T]) Refresh(newCapacity int) bool {
l.mux.Lock()
defer l.mux.Unlock()
if newCapacity >= l.likedQueue.Capacity() {
if l.likedQueue.IsFull() {
yes := l.likedQueue.Refresh(newCapacity)
if yes {
notifyNumber := newCapacity - l.likedQueue.Capacity()
for i := 0; i < notifyNumber; i++ {
blockCtxInfo, ok := l.ctxLikedQueue.Dequeue()
if ok {
//如果存在阻塞的协程,则唤醒,把添加的元素放进队列
itemPtr := blockCtxInfo.ctx.Value(itemKey).(*atomic.Pointer[T])
item := *itemPtr.Load()
blockCtxInfo.cancel()
//是没有被打断则被取消的才放入队列中
interruptPtr := blockCtxInfo.ctx.Value(interruptKey).(*atomic.Bool)
if errors.Is(blockCtxInfo.ctx.Err(), context.Canceled) && !interruptPtr.Load() {
l.likedQueue.Enqueue(item)
}
} else {
break
}
}
}
return yes
} else {
return l.likedQueue.Refresh(newCapacity)
}
} else {
return l.likedQueue.Refresh(newCapacity)
}
}
func (l *LinkedBlockingQueue[T]) Put(item T) bool {
return l.Offer(item, maxTimeDuration)
}
func (l *LinkedBlockingQueue[T]) Offer(item T, timeout time.Duration) bool {
var ctxInfo *contextInfo
ok := false
func() {
l.mux.Lock()
defer l.mux.Unlock()
if l.likedQueue.IsFull() {
if timeout > 0 {
itemPtr := &atomic.Pointer[T]{}
itemPtr.Store(&item)
interruptPtr := &atomic.Bool{}
ctx, cancel := context.WithTimeout(context.WithValue(context.WithValue(context.Background(), itemKey, itemPtr), interruptKey, interruptPtr), timeout)
ctxInfo = &contextInfo{ctx: ctx, cancel: cancel, goroutineId: GetGoroutineID()}
l.ctxLikedQueue.Enqueue(ctxInfo)
}
} else {
ok = true
for {
//判断有没有阻塞,有阻塞,则通过context传值和唤醒
blockCtxInfo, have := l.ctxLikedQueue.Dequeue()
if have {
itemPtr := blockCtxInfo.ctx.Value(itemKey).(*atomic.Pointer[T])
//没有超时和取消时,才通过context传值
if blockCtxInfo.ctx.Err() == nil {
itemPtr.Store(&item)
blockCtxInfo.cancel()
return
}
} else {
l.likedQueue.Enqueue(item)
return
}
}
}
}()
if ctxInfo != nil {
select {
case <-ctxInfo.ctx.Done():
l.mux.Lock()
defer l.mux.Unlock()
if errors.Is(ctxInfo.ctx.Err(), context.Canceled) {
//被唤醒,且没有被打断,则为添加成功
interruptPtr := ctxInfo.ctx.Value(interruptKey).(*atomic.Bool)
//判断是否是被打断
if !interruptPtr.Load() {
ok = true
}
} else {
//超时,则需要从阻塞上下文队列中删除
l.ctxLikedQueue.delete(ctxInfo, func(ctxInfoItem *contextInfo, deleteCtxInfo any) bool {
return ctxInfoItem == deleteCtxInfo.(*contextInfo)
})
}
}
}
return ok
}
func (l *LinkedBlockingQueue[T]) Take() (T, bool) {
return l.Poll(maxTimeDuration)
}
func (l *LinkedBlockingQueue[T]) Poll(timeout time.Duration) (T, bool) {
var item T
var ok = false
var ctxInfo *contextInfo
func() {
l.mux.Lock()
defer l.mux.Unlock()
if l.likedQueue.IsEmpty() {
if timeout > 0 {
itemPtr := &atomic.Pointer[T]{}
interruptPtr := &atomic.Bool{}
ctx, cancel := context.WithTimeout(context.WithValue(context.WithValue(context.Background(), itemKey, itemPtr), interruptKey, interruptPtr), timeout)
ctxInfo = &contextInfo{ctx: ctx, cancel: cancel, goroutineId: GetGoroutineID()}
l.ctxLikedQueue.Enqueue(ctxInfo)
}
} else {
ok = true
for {
//判断有没有阻塞
blockCtxInfo, have := l.ctxLikedQueue.Dequeue()
if have {
itemPtr := blockCtxInfo.ctx.Value(itemKey).(*atomic.Pointer[T])
//没有超时或者被取消时,才放入
if blockCtxInfo.ctx.Err() == nil {
//用队列的返回
item, _ = l.likedQueue.Dequeue()
//把阻塞的放回队列
newItem := *itemPtr.Load()
l.likedQueue.Enqueue(newItem)
blockCtxInfo.cancel()
return
}
} else {
item, _ = l.likedQueue.Dequeue()
return
}
}
}
}()
if ctxInfo != nil {
select {
case <-ctxInfo.ctx.Done():
l.mux.Lock()
defer l.mux.Unlock()
if errors.Is(ctxInfo.ctx.Err(), context.Canceled) {
//被唤醒。则取出数据
itemPtr := ctxInfo.ctx.Value(itemKey).(*atomic.Pointer[T])
interruptPtr := ctxInfo.ctx.Value(interruptKey).(*atomic.Bool)
if !interruptPtr.Load() {
item = *itemPtr.Load()
ok = true
}
} else {
//超时,则需要从阻塞上下文队列中删除
l.ctxLikedQueue.delete(ctxInfo, func(ctxInfoItem *contextInfo, deleteCtxInfo any) bool {
return ctxInfoItem == deleteCtxInfo.(*contextInfo)
})
}
}
}
return item, ok
}
type BlockingQueue[T any] interface {
Queue[T]
Put(item T) bool
Offer(item T, timeout time.Duration) bool
Take() (T, bool)
Interrupt(goroutineId int64)
Poll(timeout time.Duration) (T, bool)
}
// Node 定义链表节点结构体
type Node[T any] struct {
data T
next *Node[T]
}
type LinkedQueue[T any] struct {
head *Node[T]
tail *Node[T]
size int
capacity int
}
// InsertAtEnd 在链表尾部插入新节点
func (l *LinkedQueue[T]) insertAtEnd(data T) bool {
if l.IsFull() {
return false
}
newNode := &Node[T]{data: data, next: nil}
if l.head == nil {
l.head = newNode
l.tail = newNode
} else {
l.tail.next = newNode
l.tail = newNode
}
l.size++
return true
}
// DeleteAtBeginning 删除链表头部节点
func (l *LinkedQueue[T]) deleteAtHead() (T, bool) {
if l.head == nil {
var zero T
return zero, false
}
data := l.head.data
l.head = l.head.next
if l.head == nil {
l.tail = nil
}
l.size--
return data, true
}
func (l *LinkedQueue[T]) delete(data any, compare func(T, any) bool) (T, bool) {
var result T
var ok bool
// 处理头节点就是要删除的节点的情况
if l.head != nil && compare(l.head.data, data) {
result = l.head.data
ok = true
l.head = l.head.next
if l.head == nil {
l.tail = nil
}
l.size--
} else {
// 遍历链表查找要删除的节点
current := l.head
for current != nil && current.next != nil {
if compare(current.next.data, data) {
result = current.next.data
ok = true
if current.next == l.tail {
l.tail = current
}
current.next = current.next.next
l.size--
break
}
current = current.next
}
}
return result, ok
}
// IsEmpty 判断链表是否为空
func (l *LinkedQueue[T]) IsEmpty() bool {
return l.size == 0
}
func (l *LinkedQueue[T]) IsFull() bool {
return l.size == l.capacity
}
// Size 返回链表的大小
func (l *LinkedQueue[T]) Size() int {
return l.size
}
// Capacity 返回链表的容量
func (l *LinkedQueue[T]) Capacity() int {
return l.capacity
}
// Enqueue 入队操作
func (l *LinkedQueue[T]) Enqueue(item T) bool {
return l.insertAtEnd(item)
}
// Dequeue 出队操作
func (l *LinkedQueue[T]) Dequeue() (T, bool) {
return l.deleteAtHead()
}
func (l *LinkedQueue[T]) RemoveAll() []T {
result := make([]T, 0, l.size)
for {
t, ok := l.Dequeue()
if ok {
result = append(result, t)
} else {
break
}
}
return result
}
func (l *LinkedQueue[T]) Refresh(newCapacity int) bool {
ok := true
if newCapacity >= l.capacity {
l.capacity = newCapacity
} else {
if l.size > newCapacity {
ok = false
} else {
l.capacity = newCapacity
}
}
return ok
}
type LockQueue[T any] struct {
queue Queue[T]
rwMux sync.RWMutex
}
func (l *LockQueue[T]) IsEmpty() bool {
l.rwMux.RLock()
defer l.rwMux.RUnlock()
return l.queue.IsEmpty()
}
func (l *LockQueue[T]) IsFull() bool {
l.rwMux.RLock()
defer l.rwMux.RUnlock()
return l.queue.IsFull()
}
func (l *LockQueue[T]) Size() int {
l.rwMux.RLock()
defer l.rwMux.RUnlock()
return l.queue.Size()
}
func (l *LockQueue[T]) Capacity() int {
l.rwMux.RLock()
defer l.rwMux.RUnlock()
return l.queue.Capacity()
}
func (l *LockQueue[T]) Enqueue(item T) bool {
l.rwMux.Lock()
defer l.rwMux.Unlock()
return l.queue.Enqueue(item)
}
func (l *LockQueue[T]) Dequeue() (T, bool) {
l.rwMux.Lock()
defer l.rwMux.Unlock()
return l.queue.Dequeue()
}
func (l *LockQueue[T]) RemoveAll() []T {
l.rwMux.Lock()
defer l.rwMux.Unlock()
return l.queue.RemoveAll()
}
func (l *LockQueue[T]) Refresh(newCapacity int) bool {
l.rwMux.Lock()
defer l.rwMux.Unlock()
ok := l.queue.Refresh(newCapacity)
return ok
}
type Queue[T any] interface {
IsEmpty() bool
IsFull() bool
Size() int
Capacity() int
Enqueue(item T) bool
Dequeue() (T, bool)
RemoveAll() []T
Refresh(newCapacity int) bool
}