golang分片map的实现

2022-04-09  本文已影响0人  bug去无踪
package main

import (
    "errors"
    "fmt"
    "hash/crc32"
    "sync"
    "time"
)

type MapArr struct {
    sync.RWMutex
    data map[string]uint8
}
type MapList []*MapArr

func main() {
    a := NewArrayMap(10)
    go func() {
        a.Add("1")
    }()
    go func() {
        a.Add("2")
    }()
    go func() {
        a.Add("3")
    }()
    go func() {
        a.Add("4")
    }()
    go func() {
        a.Add("9")
    }()

    go func() {
        vv, _ := a.get("4")
        fmt.Println("获取结果:", vv)

    }()
    time.Sleep(time.Second * 5)
    fmt.Println(a)
    vv, _ := a.get("4")
    fmt.Println("获取结果:", vv)

}

func NewArrayMap(cap int) MapList {
    s := make([]*MapArr, cap)
    for i := 0; i < cap; i++ {
        temp := MapArr{data: make(map[string]uint8)}
        s[i] = &temp
    }
    return MapList(s)
}

func (list MapList) Add(key string) error {
    index := int((crc32.ChecksumIEEE([]byte(key)) % 10))
    list[index].Lock()
    defer list[index].Unlock()
    list[index].data[key] = 1

    return nil
}
func (list MapList) get(key string) (uint8, error) {
    index := int((crc32.ChecksumIEEE([]byte(key)) % 10))
    list[index].RLock()
    defer list[index].RUnlock()
    if list[index] != nil {
        if v, ok := list[index].data[key]; ok {
            return v, nil
        }
    }
    return 0, errors.New("key不存在")
}
上一篇 下一篇

猜你喜欢

热点阅读