go实现并发安全hashtable 拉链法

在这个实现中,HashTable包含多个bucket,每个bucket都有一个互斥锁来保证并发安全。Put方法用于插入键值对,Get方法用于获取值,Delete方法用于删除键值对。通过哈希函数确定键应该存储在哪个bucket中,然后在对应的bucket中进行操作。这种实现方式可以有效地处理并发访问,确保哈希表在多线程环境下的正确性。

go 复制代码
package main

import (
    "sync"
)

type HashTable struct {
    buckets    []*bucket
    bucketSize int
}

type bucket struct {
    mu     sync.Mutex
    items  map[string]interface{}
}

func NewHashTable(bucketSize int) *HashTable {
    buckets := make([]*bucket, bucketSize)
    for i := range buckets {
        buckets[i] = &bucket{
            items: make(map[string]interface{}),
        }
    }
    return &HashTable{
        buckets:    buckets,
        bucketSize: bucketSize,
    }
}

func (ht *HashTable) hash(key string) int {
    hashValue := 0
    for _, char := range key {
        hashValue += int(char)
    }
    return hashValue % ht.bucketSize
}

func (ht *HashTable) Put(key string, value interface{}) {
    bucketIndex := ht.hash(key)
    bucket := ht.buckets[bucketIndex]
    bucket.mu.Lock()
    bucket.items[key] = value
    bucket.mu.Unlock()
}

func (ht *HashTable) Get(key string) (interface{}, bool) {
    bucketIndex := ht.hash(key)
    bucket := ht.buckets[bucketIndex]
    bucket.mu.Lock()
    value, ok := bucket.items[key]
    bucket.mu.Unlock()
    return value, ok
}

func (ht *HashTable) Delete(key string) {
    bucketIndex := ht.hash(key)
    bucket := ht.buckets[bucketIndex]
    bucket.mu.Lock()
    delete(bucket.items, key)
    bucket.mu.Unlock()
}



func main() {
    ht := NewHashTable(10)

    // 并发安全地插入数据
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            ht.Put(fmt.Sprintf("key%d", i), i)
        }(i)
    }
    wg.Wait()

    // 并发安全地读取数据
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            value, ok := ht.Get(fmt.Sprintf("key%d", i))
            if ok {
                fmt.Println(value)
            }
        }(i)
    }
    wg.Wait()

    // 并发安全地删除数据
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            ht.Delete(fmt.Sprintf("key%d", i))
        }(i)
    }
    wg.Wait()
}
相关推荐
星夜离尘564 分钟前
MATLAB阶跃响应怎么量:别把最后一个采样点当成稳态
开发语言·matlab
云水初17 分钟前
【agent篇】RAG Agent避坑指南(附高级RAG Agent汇总)
开发语言·笔记·python·学习·langchain·agent·rag
Littlehero_12119 分钟前
QT自定义控件之水泥厂组态(源码开源)
开发语言·qt
辛苦才能28 分钟前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
m0_6399069431 分钟前
HashMap:哈希扰动、扩容源码、红黑树转换、并发问题
java·算法·哈希算法
miller-tsunami39 分钟前
STL简介&string相关知识点
开发语言·c++·string
半摆烂日常1 小时前
手机表单的左滑操作:触摸事件的处理细节
大数据·开发语言·人工智能·智能手机·https·c#
星夜离尘562 小时前
MATLAB滑动RMS如何接报警:窗口未满和缺样不能当成正常
开发语言·matlab
开开心心就好2 小时前
白天晚上自动调蓝光,护眼工具亮度可调
服务器·开发语言·算法·pdf·ocr·intellij-idea·idea
张张123y2 小时前
后端第十一课:RAG 落地实战(从 0 到 1 接上私有知识库,并设计一个好用的 RAG)
开发语言·人工智能·python·机器学习·fastapi·rag