concurrent-map 项目教程
concurrent-maplock-free B+ tree项目地址:https://gitcode.com/gh_mirrors/con/concurrent-map
1. 项目的目录结构及介绍
concurrent-map/
├── LICENSE
├── README.md
├── concurrent_map.go
├── concurrent_map_bench_test.go
├── concurrent_map_test.go
├── go.mod
└── go.sum
- LICENSE: 项目的许可证文件。
- README.md: 项目的说明文档。
- concurrent_map.go: 并发安全 map 的核心实现文件。
- concurrent_map_bench_test.go: 性能测试文件。
- concurrent_map_test.go: 单元测试文件。
- go.mod: Go 模块文件,定义了项目的依赖。
- go.sum: Go 模块的校验文件。
2. 项目的启动文件介绍
项目的启动文件是 concurrent_map.go
,其中包含了并发安全 map 的核心实现。以下是文件的主要内容:
package cmap
import (
"hash/fnv"
"sync"
)
var SHARD_COUNT = 32
// A "thread" safe map of type string:Anything.
// To avoid lock bottlenecks this map is dived to several (SHARD_COUNT) map shards.
type ConcurrentMap []*ConcurrentMapShared
// A "thread" safe string to anything map.
type ConcurrentMapShared struct {
items map[string]interface{}
sync.RWMutex // Read Write mutex, guards access to internal map.
}
// Creates a new concurrent map.
func New() ConcurrentMap {
m := make(ConcurrentMap, SHARD_COUNT)
for i := 0; i < SHARD_COUNT; i++ {
m[i] = &ConcurrentMapShared{items: make(map[string]interface{})}
}
return m
}
// GetShard returns shard under given key
func (m ConcurrentMap) GetShard(key string) *ConcurrentMapShared {
hasher := fnv.New32()
hasher.Write([]byte(key))
return m[hasher.Sum32()%uint32(SHARD_COUNT)]
}
// Set sets the value under the specified key.
func (m ConcurrentMap) Set(key string, value interface{}) {
shard := m.GetShard(key)
shard.Lock()
shard.items[key] = value
shard.Unlock()
}
// Get retrieves an element from map under given key.
func (m ConcurrentMap) Get(key string) (interface{}, bool) {
shard := m.GetShard(key)
shard.RLock()
val, ok := shard.items[key]
shard.RUnlock()
return val, ok
}
3. 项目的配置文件介绍
项目中没有显式的配置文件,所有的配置都是通过代码中的常量和函数参数来完成的。例如,SHARD_COUNT
定义了分片的数量,可以在 concurrent_map.go
文件中进行修改。
var SHARD_COUNT = 32
这个值决定了并发安全 map 的分片数量,可以根据实际需求进行调整。
concurrent-maplock-free B+ tree项目地址:https://gitcode.com/gh_mirrors/con/concurrent-map