登录
首页 >  Golang >  Go问答

在并发环境下使用互斥锁进行映射写入

来源:stackoverflow

时间:2024-03-01 11:36:23 313浏览 收藏

今天golang学习网给大家带来了《在并发环境下使用互斥锁进行映射写入》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我有一张地图,想手动进一步分片,简化的代码是

const (
    dictShardNum = 16
    dictShardSize = 1 << 28
)

type shard struct {
    mu sync.Mutex
    m  map[int64]uint32
}

type dict struct {
    shards []shard
}

func newDict() *dict {
   shards := make([]shard, 0, dictShardNum)
   for i := 0; i < dictShardNum; i++ {
      shards = append(shards, shard{ m: make(map[int64]uint32) })
   }
   return &dict{ shards }
}

func (d *dict) insert(n int64) uint32 {
    shardNum := int(n % dictShardNum)
    shard := d.shards[shardNum]
    shard.mu.Lock()
    defer shard.mu.Unlock()

    tempID, ok := shard.m[n]
    if !ok {
        tempID = uint32(len(shard.m) + shardNum*dictShardSize)
        shard.m[n] = tempID   // fatal error: concurrent map writes
    }
    return tempID
}

运行时出现 fatal 错误:并发映射在该行写入 ,但我确实锁定了互斥体,不确定我的代码出了什么问题


解决方案


您的代码无法编译!

演示:https://play.golang.org/p/6AwS0vOZfeP

25:18: undefined: n
30:24: undefined: n
33:11: undefined: n

如果我将 v int64 更改为 n int64

$ go vet mutex.go
./mutex.go:26:11: assignment copies lock value to shard: command-line-arguments.shard contains sync.mutex
$

演示:https://play.golang.org/p/jExE-m11ny5

package main

import (
    "sync"
)

const (
    dictShardNum  = 16
    dictShardSize = 1 << 28
)

type shard struct {
    mu sync.Mutex
    m  map[int64]uint32
}

type dict struct {
    shards []shard
}

/// a newDict function

func (d *dict) insert(n int64) uint32 {
    shardNum := int(n % dictShardNum)
    shard := d.shards[shardNum]
    shard.mu.Lock()
    defer shard.mu.Unlock()

    tempID, ok := shard.m[n]
    if !ok {
        tempID = uint32(len(shard.m) + shardNum*dictShardSize)
        shard.m[n] = tempID // fatal error: concurrent map writes
    }
    return tempID
}

func main() {}

好了,本文到此结束,带大家了解了《在并发环境下使用互斥锁进行映射写入》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>