Created
May 16, 2024 10:51
-
-
Save daaku/f11b3078fa45ead45f37de293fe402e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"sync/atomic" | |
) | |
type ShardedConcurrentSlice[T any] struct { | |
datas [][]T | |
mu []sync.Mutex | |
next atomic.Int64 | |
} | |
func NewShardedConcurrentSlice[T any](numShards int, prealloc int) *ShardedConcurrentSlice[T] { | |
datas := make([][]T, numShards) | |
for i := range datas { | |
datas[i] = make([]T, 0, prealloc) | |
} | |
return &ShardedConcurrentSlice[T]{ | |
datas: datas, | |
mu: make([]sync.Mutex, numShards), | |
} | |
} | |
func (s *ShardedConcurrentSlice[T]) Append(v T) { | |
shard := int(s.next.Add(1)) % len(s.datas) | |
s.mu[shard].Lock() | |
s.datas[shard] = append(s.datas[shard], v) | |
s.mu[shard].Unlock() | |
} | |
func (s *ShardedConcurrentSlice[T]) Data() [][]T { | |
return s.datas | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment