go-study/lock_free/delay_queue.go
2024-12-03 11:19:18 +08:00

33 lines
673 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package lock_free
import "time"
type DelayLkQueue[T any] struct {
LkQueue[T]
}
// NewDelayLkQueue 创建延迟无锁队列
func NewDelayLkQueue[T any]() *DelayLkQueue[T] {
return &DelayLkQueue[T]{*NewLkQueue[T]()}
}
// DelayEnqueue 延迟入队
func (q *DelayLkQueue[T]) DelayEnqueue(value T, duration time.Duration) {
time.AfterFunc(duration, func() {
q.Enqueue(value)
})
}
// ContinuousDequeue 持续监听出队通知
func (q *DelayLkQueue[T]) ContinuousDequeue(notify ...chan T) {
for {
if value, ok := q.Dequeue(); ok {
for _, n := range notify {
n <- value
}
} else {
time.Sleep(time.Millisecond) // 队列为空休眠1毫秒
}
}
}