优化延迟无锁队列,增加迭代器方法
This commit is contained in:
parent
0ec5a62438
commit
210b60011e
@ -1,6 +1,9 @@
|
||||
package lock_free
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"iter"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DelayLkQueue[T any] struct {
|
||||
LkQueue[T]
|
||||
@ -18,15 +21,33 @@ func (q *DelayLkQueue[T]) DelayEnqueue(value T, duration time.Duration) {
|
||||
})
|
||||
}
|
||||
|
||||
// ContinuousDequeue 持续监听出队通知
|
||||
func (q *DelayLkQueue[T]) ContinuousDequeue(notify ...chan T) {
|
||||
for {
|
||||
if value, ok := q.Dequeue(); ok {
|
||||
for _, n := range notify {
|
||||
n <- value
|
||||
// ContinuousDequeue 持续监听出队
|
||||
func (q *DelayLkQueue[T]) ContinuousDequeue() iter.Seq[T] {
|
||||
return func(yield func(T) bool) {
|
||||
for {
|
||||
if value, ok := q.Dequeue(); ok {
|
||||
if !yield(value) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
time.Sleep(time.Millisecond) // 队列为空,休眠1毫秒
|
||||
}
|
||||
} else {
|
||||
time.Sleep(time.Millisecond) // 队列为空,休眠1毫秒
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ContinuousDequeueExecute 持续监听出队执行函数
|
||||
func (q *DelayLkQueue[T]) ContinuousDequeueExecute(fn func(T)) {
|
||||
for value := range q.ContinuousDequeue() {
|
||||
fn(value)
|
||||
}
|
||||
}
|
||||
|
||||
// ContinuousDequeueNotify 持续监听出队通知
|
||||
func (q *DelayLkQueue[T]) ContinuousDequeueNotify(chs ...chan T) {
|
||||
q.ContinuousDequeueExecute(func(value T) {
|
||||
for _, ch := range chs {
|
||||
ch <- value
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -27,7 +27,7 @@ func TestDelayLkQueue(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
go q.ContinuousDequeue(notify)
|
||||
go q.ContinuousDequeueNotify(notify)
|
||||
time.Sleep(time.Second * 5)
|
||||
close(notify)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user