增加延迟无锁队列创建选项

This commit is contained in:
fantasticbin 2024-12-03 11:14:58 +08:00
parent 6f0dd4955d
commit 75acf1f3dd
3 changed files with 34 additions and 4 deletions

View File

@ -3,12 +3,14 @@ package lock_free
import "time"
type DelayLkQueue[T any] struct {
gap time.Duration // 控制监听重试间隔
LkQueue[T]
}
// NewDelayLkQueue 创建延迟无锁队列
func NewDelayLkQueue[T any]() *DelayLkQueue[T] {
return &DelayLkQueue[T]{*NewLkQueue[T]()}
func NewDelayLkQueue[T any](opt ...Option) *DelayLkQueue[T] {
opts := loadOptions(opt...)
return &DelayLkQueue[T]{opts.gap, *NewLkQueue[T]()}
}
// DelayEnqueue 延迟入队
@ -26,7 +28,7 @@ func (q *DelayLkQueue[T]) ContinuousDequeue(notify ...chan T) {
n <- value
}
} else {
time.Sleep(time.Millisecond) // 队列为空休眠1毫秒
time.Sleep(q.gap) // 队列为空,休眠重试
}
}
}

View File

@ -13,7 +13,7 @@ func TestDelayLkQueue(t *testing.T) {
{1, time.Second},
{3, time.Second * 3},
}
q := NewDelayLkQueue[int]()
q := NewDelayLkQueue[int](WithGap(time.Millisecond * 100))
for _, c := range cases {
q.DelayEnqueue(c.value, c.duration)

28
lock_free/options.go Normal file
View File

@ -0,0 +1,28 @@
package lock_free
import "time"
// Options 无锁队列选项
type Options struct {
gap time.Duration
}
type Option func(*Options)
func loadOptions(opt ...Option) Options {
opts := Options{
gap: time.Millisecond,
}
for _, o := range opt {
o(&opts)
}
return opts
}
func WithGap(gap time.Duration) Option {
return func(o *Options) {
o.gap = gap
}
}