优化map

This commit is contained in:
kercylan98 2023-05-19 09:34:20 +08:00
parent 4565edb6d7
commit 5488b3d455
4 changed files with 37 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package asynchronization
import (
"encoding/json"
"github.com/kercylan98/minotaur/utils/hash"
)
func NewMap[Key comparable, value any]() *Map[Key, value] {
@ -33,7 +34,7 @@ func (slf *Map[Key, Value]) AtomGetSet(key Key, handle func(value Value, exist b
}
// Atom 原子操作
func (slf *Map[Key, Value]) Atom(handle func(m *Map[Key, Value])) {
func (slf *Map[Key, Value]) Atom(handle func(m hash.Map[Key, Value])) {
handle(slf)
}

29
utils/hash/map.go Normal file
View File

@ -0,0 +1,29 @@
package hash
// Map 提供了map集合接口
type Map[Key comparable, Value any] interface {
Set(key Key, value Value)
Get(key Key) Value
// AtomGetSet 原子方式获取一个值并在之后进行赋值
AtomGetSet(key Key, handle func(value Value, exist bool) (newValue Value, isSet bool))
// Atom 原子操作
Atom(handle func(m Map[Key, Value]))
Exist(key Key) bool
GetExist(key Key) (Value, bool)
Delete(key Key)
DeleteGet(key Key) Value
DeleteGetExist(key Key) (Value, bool)
DeleteExist(key Key) bool
Clear()
ClearHandle(handle func(key Key, value Value))
Range(handle func(key Key, value Value))
RangeSkip(handle func(key Key, value Value) bool)
RangeBreakout(handle func(key Key, value Value) bool)
RangeFree(handle func(key Key, value Value, skip func(), breakout func()))
Keys() []Key
Slice() []Value
Map() map[Key]Value
Size() int
// GetOne 获取一个
GetOne() (value Value)
}

View File

@ -2,6 +2,7 @@ package synchronization
import (
"encoding/json"
"github.com/kercylan98/minotaur/utils/hash"
"sync"
)
@ -47,7 +48,7 @@ func (slf *Map[Key, Value]) AtomGetSet(key Key, handle func(value Value, exist b
}
// Atom 原子操作
func (slf *Map[Key, Value]) Atom(handle func(m *Map[Key, Value])) {
func (slf *Map[Key, Value]) Atom(handle func(m hash.Map[Key, Value])) {
slf.lock.Lock()
slf.atom = true
handle(slf)

View File

@ -28,6 +28,10 @@ type MapSegment[Key comparable, Value any] struct {
lock sync.RWMutex
}
func (slf *MapSegment[Key, Value]) Atom(handle func(m hash.Map[Key, Value])) {
panic("this function is currently not supported")
}
func (slf *MapSegment[Key, Value]) Set(key Key, value Value) {
slf.lock.RLock()
s, exist := slf.cache[key]