无锁队列及队列集合增加长度获取功能

This commit is contained in:
fantasticbin 2024-12-10 08:53:30 +08:00
parent f36180bc8a
commit c9632e7ab1
3 changed files with 29 additions and 0 deletions

View File

@ -64,6 +64,15 @@ func (q *LkQueue[T]) Dequeue() (value T, ok bool) {
}
}
// Len 队列长度
func (q *LkQueue[T]) Len() int {
var count int
for node := load[T](&q.head); node != nil; node = load[T](&node.next) {
count++
}
return count - 1 // 减去头节点
}
// load 读取节点的值
func load[T any](p *unsafe.Pointer) *node[T] {
return (*node[T])(atomic.LoadPointer(p))

View File

@ -35,6 +35,14 @@ func (q *Queues[TKey, TValue, TRoute]) Dequeue(route TRoute) (value TValue, ok b
return value, false
}
// Len 队列长度
func (q *Queues[TKey, TValue, TRoute]) Len(route TRoute) int {
if queue, ok := q.queues.Load(route); ok {
return queue.(*DelayLkQueue[TKey, TValue]).Len()
}
return 0
}
// DelayEnqueue 延迟入队
func (q *Queues[TKey, TValue, TRoute]) DelayEnqueue(route TRoute, value TValue, duration time.Duration) {
if queue, ok := q.queues.Load(route); ok {

View File

@ -16,6 +16,18 @@ func TestQueues(t *testing.T) {
route := "test"
q := NewQueues[struct{}, int, string]()
for _, c := range cases {
q.Enqueue(route, c.value)
}
if q.Len(route) != len(cases) {
t.Errorf("queue length error, want %d, got %d", len(cases), q.Len(route))
}
for range cases {
q.Dequeue(route)
}
for _, c := range cases {
q.DelayEnqueue(route, c.value, c.duration)
}