concurrent-map 项目教程

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石喜宏Melinda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值