aboutsummaryrefslogtreecommitdiff
path: root/shards.go
diff options
context:
space:
mode:
authoralex <[email protected]>2026-07-08 21:20:20 +0200
committeralex <[email protected]>2026-07-08 21:20:20 +0200
commit8fc42bccbe1445d538674a50567df17fbfc4874d (patch)
tree4b9f541200a06aab615bad7738275fadb52a34ac /shards.go
parent917b08a98cb310d05170d2ef3de9847419e3990e (diff)
downloadredis-clone-8fc42bccbe1445d538674a50567df17fbfc4874d.tar.xz
redis-clone-8fc42bccbe1445d538674a50567df17fbfc4874d.zip
changed shards struct to use RWMutex and added executeRead
Diffstat (limited to 'shards.go')
-rw-r--r--shards.go63
1 files changed, 38 insertions, 25 deletions
diff --git a/shards.go b/shards.go
index ae6e069..279d9b1 100644
--- a/shards.go
+++ b/shards.go
@@ -6,7 +6,7 @@ import (
"sync"
)
type Shard struct{
- mu sync.Mutex
+ mu sync.RWMutex
id int
data map[string]Item
}
@@ -25,30 +25,43 @@ func (db *RedisDB) Execute(key string, fn func(*Shard) interface{}) interface{}
defer shard.mu.Unlock()
return fn(shard)
}
-
+func (db *RedisDB) ExecuteRead(key string, fn func(*Shard) interface{}) interface{} {
+ shard := db.getShard(key)
+ shard.mu.RLock()
+ defer shard.mu.RUnlock()
+ return fn(shard)
+}
func ( db *RedisDB) ExecuteMulti(keys []string, fn func([]*Shard) interface{})interface{}{
- shardMap := make(map[int]*Shard)
- for _, k := range keys {
- shard := db.getShard(k)
- shardMap[shard.id] = shard
- }
- var sortedIDs []int
- for id := range shardMap {
- sortedIDs = append(sortedIDs, id)
- }
- sort.Ints(sortedIDs)
- for _, id := range sortedIDs{
- shardMap[id].mu.Lock()
- }
- defer func(){
- for i := len(sortedIDs)-1; i >= 0; i --{
- shardMap[sortedIDs[i]].mu.Unlock()
+ if len(keys) == 1{
+ shard := db.getShard(keys[0])
+ shard.mu.Lock()
+ defer shard.mu.Unlock()
+ shards := []*Shard{shard}
+ return fn(shards)
+ }else{
+ shardMap := make(map[int]*Shard)
+ for _, k := range keys {
+ shard := db.getShard(k)
+ shardMap[shard.id] = shard
}
- }()
-
- shards := make([]*Shard, 0, len(shardMap))
- for _, id := range sortedIDs {
- shards = append(shards, shardMap[id])
- }
- return fn(shards)
+ var sortedIDs []int
+ for id := range shardMap {
+ sortedIDs = append(sortedIDs, id)
+ }
+ sort.Ints(sortedIDs)
+ for _, id := range sortedIDs{
+ shardMap[id].mu.Lock()
+ }
+ defer func(){
+ for i := len(sortedIDs)-1; i >= 0; i --{
+ shardMap[sortedIDs[i]].mu.Unlock()
+ }
+ }()
+
+ shards := make([]*Shard, 0, len(shardMap))
+ for _, id := range sortedIDs {
+ shards = append(shards, shardMap[id])
+ }
+ return fn(shards)
+ }
}