Files
web_hgcg_server/pub/common/lock/queue.go
T
2026-10-27 16:44:55 +08:00

76 lines
1.4 KiB
Go

package lock
import "sync"
// Queue 定义一个泛型队列结构
type Queue[T any] struct {
items []T
lock sync.RWMutex // 添加读写锁
}
// NewQueue 创建一个新的队列
func NewQueue[T any]() *Queue[T] {
return &Queue[T]{
items: make([]T, 0),
}
}
// Enqueue 入队操作 - 将元素添加到队列末尾
func (q *Queue[T]) Enqueue(item T) {
q.lock.Lock() // 写操作需要写锁
defer q.lock.Unlock()
q.items = append(q.items, item)
}
// Dequeue 出队操作 - 从队列头部移除并返回元素
func (q *Queue[T]) Dequeue() (T, bool) {
q.lock.Lock() // 写操作需要写锁
defer q.lock.Unlock()
var zero T
if len(q.items) == 0 {
return zero, false
}
item := q.items[0]
q.items = q.items[1:]
return item, true
}
// Peek 查看队列头部元素但不移除
func (q *Queue[T]) Peek() (T, bool) {
q.lock.RLock() // 读操作使用读锁
defer q.lock.RUnlock()
var zero T
if len(q.items) == 0 {
return zero, false
}
return q.items[0], true
}
// IsEmpty 检查队列是否为空
func (q *Queue[T]) IsEmpty() bool {
q.lock.RLock() // 读操作使用读锁
defer q.lock.RUnlock()
return len(q.items) == 0
}
// Size 返回队列中的元素个数
func (q *Queue[T]) Size() int {
q.lock.RLock() // 读操作使用读锁
defer q.lock.RUnlock()
return len(q.items)
}
// Clear 清空队列
func (q *Queue[T]) Clear() {
q.lock.Lock() // 写操作需要写锁
defer q.lock.Unlock()
q.items = make([]T, 0)
}