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()
}
相关推荐
花酒锄作田20 小时前
Go - Zerolog使用入门
golang
花酒锄作田13 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理13 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12313 天前
matlab画图工具
开发语言·matlab
dustcell.13 天前
haproxy七层代理
java·开发语言·前端
norlan_jame13 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone13 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549613 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月13 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_5312371713 天前
C语言-数组练习进阶
c语言·开发语言·算法