goProject/trunk/center/common/cache/cacheslice.go
皮蛋13361098506 1b77f62820 初始化项目
2025-01-06 16:01:02 +08:00

49 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cache
import (
"sync"
)
// SliceCache结构体代表基于切片的缓存内部使用切片存储元素并通过读写锁保证并发安全
type SliceCache struct {
data []interface{}
rwmu sync.RWMutex
}
// NewSliceCache创建并返回一个新的基于切片的缓存实例
func NewSliceCache() *SliceCache {
return &SliceCache{
data: make([]interface{}, 0),
}
}
// Add方法用于向切片缓存中添加元素写操作加写锁保证并发安全
func (sc *SliceCache) Add(element interface{}) {
sc.rwmu.Lock()
sc.data = append(sc.data, element)
sc.rwmu.Unlock()
}
// GetAll方法用于获取切片缓存中的所有元素读操作加读锁允许并发读
func (sc *SliceCache) GetAll() []interface{} {
sc.rwmu.RLock()
result := make([]interface{}, len(sc.data))
copy(result, sc.data)
sc.rwmu.RUnlock()
return result
}
// Remove方法用于从切片缓存中删除指定元素写操作加写锁保证并发安全
func (sc *SliceCache) Remove(element interface{}) bool {
sc.rwmu.Lock()
for i, e := range sc.data {
if e == element {
sc.data = append(sc.data[:i], sc.data[i+1:]...)
sc.rwmu.Unlock()
return true
}
}
sc.rwmu.Unlock()
return false
}