seaweedfs/weed/util/queue.go

64 lines
718 B
Go
Raw Normal View History

package util
2024-06-29 05:57:20 +08:00
import (
"sync"
)
2024-06-29 05:57:20 +08:00
type node[T any]struct {
data T
next *node[T]
}
2024-06-29 05:57:20 +08:00
type Queue[T any] struct {
head *node[T]
tail *node[T]
count int
sync.RWMutex
}
2024-06-29 05:57:20 +08:00
func NewQueue[T any]() *Queue[T] {
q := &Queue[T]{}
return q
}
2024-06-29 05:57:20 +08:00
func (q *Queue[T]) Len() int {
q.RLock()
defer q.RUnlock()
return q.count
}
2024-06-29 05:57:20 +08:00
func (q *Queue[T]) Enqueue(item T) {
q.Lock()
defer q.Unlock()
2024-06-29 05:57:20 +08:00
n := &node[T]{data: item}
if q.tail == nil {
q.tail = n
q.head = n
} else {
q.tail.next = n
q.tail = n
}
q.count++
}
2024-06-29 05:57:20 +08:00
func (q *Queue[T]) Dequeue() (result T) {
q.Lock()
defer q.Unlock()
if q.head == nil {
2024-06-29 05:57:20 +08:00
return
}
n := q.head
q.head = n.next
if q.head == nil {
q.tail = nil
}
q.count--
return n.data
2019-12-09 11:44:16 +08:00
}