mirror of
https://github.com/charlienet/go-mixed.git
synced 2026-07-14 08:17:26 +08:00
c44a325384
locker: 导出 RWLocker/EmptyLocker 接口, 新增 WithRWLocker, 重构 SourceLocker 竞态、Synchronize 数据竞态 collections/linked_list: 补齐 ForEach/Size/GetAt/RemoveAt/ToList 等方法的锁保护 collections/queue,stack: Peek/Size/IsEmpty 加锁 collections/list/linked_list: Front/Back/GetAt 加锁 maps: rwlock_map.Exist/Count, hash_map.Count 加锁 delay_queue/mem_store: Pop 原子化、Len/IsEmpty 加锁 cleanup_guard: Run() 检查 enable 标志 sets/ketama: 修复接口变更导致的 nil 空指针
84 lines
1.3 KiB
Go
84 lines
1.3 KiB
Go
package collections
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
var _ Queue[string] = &ArrayQueue[string]{}
|
|
|
|
// 数组队列,先进先出
|
|
type ArrayQueue[T any] struct {
|
|
array []T // 底层切片
|
|
size int // 队列的元素数量
|
|
lock sync.Mutex // 为了并发安全使用的锁
|
|
}
|
|
|
|
func NewArrayQueue[T any]() *ArrayQueue[T] {
|
|
return &ArrayQueue[T]{}
|
|
}
|
|
|
|
// 入队
|
|
func (q *ArrayQueue[T]) Put(v T) {
|
|
q.lock.Lock()
|
|
defer q.lock.Unlock()
|
|
|
|
// 放入切片中,后进的元素放在数组最后面
|
|
q.array = append(q.array, v)
|
|
|
|
// 队中元素数量+1
|
|
q.size = q.size + 1
|
|
}
|
|
|
|
// 出队
|
|
func (q *ArrayQueue[T]) Poll() T {
|
|
q.lock.Lock()
|
|
defer q.lock.Unlock()
|
|
|
|
// 队中元素已空
|
|
if q.size == 0 {
|
|
panic("empty")
|
|
}
|
|
|
|
// 队列最前面元素
|
|
v := q.array[0]
|
|
|
|
// 创建新的数组,移动次数过多
|
|
newArray := make([]T, q.size-1)
|
|
for i := 1; i < q.size; i++ {
|
|
copy(newArray, q.array[1:])
|
|
}
|
|
|
|
q.array = newArray
|
|
|
|
// 队中元素数量-1
|
|
q.size = q.size - 1
|
|
return v
|
|
}
|
|
|
|
func (q *ArrayQueue[T]) Peek() T {
|
|
q.lock.Lock()
|
|
defer q.lock.Unlock()
|
|
|
|
if q.size == 0 {
|
|
panic("empty")
|
|
}
|
|
|
|
return q.array[0]
|
|
}
|
|
|
|
// 栈大小
|
|
func (q *ArrayQueue[T]) Size() int {
|
|
q.lock.Lock()
|
|
defer q.lock.Unlock()
|
|
|
|
return q.size
|
|
}
|
|
|
|
// 栈是否为空
|
|
func (q *ArrayQueue[T]) IsEmpty() bool {
|
|
q.lock.Lock()
|
|
defer q.lock.Unlock()
|
|
|
|
return q.size == 0
|
|
}
|