2024-12-03 10:10:02 +08:00
|
|
|
|
package lock_free
|
|
|
|
|
|
2024-12-03 13:01:11 +08:00
|
|
|
|
import (
|
|
|
|
|
"iter"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
2024-12-03 10:10:02 +08:00
|
|
|
|
|
|
|
|
|
type DelayLkQueue[T any] struct {
|
|
|
|
|
LkQueue[T]
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-03 10:25:34 +08:00
|
|
|
|
// NewDelayLkQueue 创建延迟无锁队列
|
2024-12-03 11:19:18 +08:00
|
|
|
|
func NewDelayLkQueue[T any]() *DelayLkQueue[T] {
|
|
|
|
|
return &DelayLkQueue[T]{*NewLkQueue[T]()}
|
2024-12-03 10:25:34 +08:00
|
|
|
|
}
|
|
|
|
|
|
2024-12-03 10:10:02 +08:00
|
|
|
|
// DelayEnqueue 延迟入队
|
|
|
|
|
func (q *DelayLkQueue[T]) DelayEnqueue(value T, duration time.Duration) {
|
|
|
|
|
time.AfterFunc(duration, func() {
|
|
|
|
|
q.Enqueue(value)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-03 13:01:11 +08:00
|
|
|
|
// 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毫秒
|
2024-12-03 10:32:08 +08:00
|
|
|
|
}
|
2024-12-03 10:10:02 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-12-03 13:01:11 +08:00
|
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|