@@ -6,10 +6,10 @@ import (
6
6
"sync"
7
7
)
8
8
9
- var SHARD_COUNT = 32
9
+ const SHARD_COUNT = 32
10
10
11
11
// A "thread" safe map of type string:Anything.
12
- // To avoid lock bottlenecks this map is dived to several (SHARD_COUNT ) map shards.
12
+ // To avoid lock bottlenecks this map is dived to several (len(m) ) map shards.
13
13
type ConcurrentMap []* ConcurrentMapShared
14
14
15
15
// A "thread" safe string to anything map.
@@ -19,9 +19,15 @@ type ConcurrentMapShared struct {
19
19
}
20
20
21
21
// Creates a new concurrent map.
22
- func New () ConcurrentMap {
23
- m := make (ConcurrentMap , SHARD_COUNT )
24
- for i := 0 ; i < SHARD_COUNT ; i ++ {
22
+ func New (shardCount ... int ) ConcurrentMap {
23
+ var nShards int
24
+ if len (shardCount ) > 0 {
25
+ nShards = shardCount [0 ]
26
+ } else {
27
+ nShards = SHARD_COUNT
28
+ }
29
+ m := make (ConcurrentMap , nShards )
30
+ for i := 0 ; i < nShards ; i ++ {
25
31
m [i ] = & ConcurrentMapShared {items : make (map [string ]interface {})}
26
32
}
27
33
return m
@@ -31,7 +37,7 @@ func New() ConcurrentMap {
31
37
func (m ConcurrentMap ) GetShard (key string ) * ConcurrentMapShared {
32
38
hasher := fnv .New32 ()
33
39
hasher .Write ([]byte (key ))
34
- return m [uint (hasher .Sum32 ())% uint (SHARD_COUNT )]
40
+ return m [uint (hasher .Sum32 ())% uint (len ( m ) )]
35
41
}
36
42
37
43
func (m ConcurrentMap ) MSet (data map [string ]interface {}) {
@@ -79,7 +85,7 @@ func (m ConcurrentMap) Get(key string) (interface{}, bool) {
79
85
// Returns the number of elements within the map.
80
86
func (m ConcurrentMap ) Count () int {
81
87
count := 0
82
- for i := 0 ; i < SHARD_COUNT ; i ++ {
88
+ for i := 0 ; i < len ( m ) ; i ++ {
83
89
shard := m [i ]
84
90
shard .RLock ()
85
91
count += len (shard .items )
@@ -126,7 +132,7 @@ func (m ConcurrentMap) Iter() <-chan Tuple {
126
132
ch := make (chan Tuple )
127
133
go func () {
128
134
wg := sync.WaitGroup {}
129
- wg .Add (SHARD_COUNT )
135
+ wg .Add (len ( m ) )
130
136
// Foreach shard.
131
137
for _ , shard := range m {
132
138
go func (shard * ConcurrentMapShared ) {
@@ -150,7 +156,7 @@ func (m ConcurrentMap) IterBuffered() <-chan Tuple {
150
156
ch := make (chan Tuple , m .Count ())
151
157
go func () {
152
158
wg := sync.WaitGroup {}
153
- wg .Add (SHARD_COUNT )
159
+ wg .Add (len ( m ) )
154
160
// Foreach shard.
155
161
for _ , shard := range m {
156
162
go func (shard * ConcurrentMapShared ) {
@@ -188,7 +194,7 @@ func (m ConcurrentMap) Keys() []string {
188
194
go func () {
189
195
// Foreach shard.
190
196
wg := sync.WaitGroup {}
191
- wg .Add (SHARD_COUNT )
197
+ wg .Add (len ( m ) )
192
198
for _ , shard := range m {
193
199
go func (shard * ConcurrentMapShared ) {
194
200
// Foreach key, value pair.
0 commit comments