gpt4 book ai didi

debugging - Golang 在 map[string]int 上与 sync.Mutex 竞赛

转载 作者:IT王子 更新时间:2023-10-29 01:58:23 29 4
gpt4 key购买 nike

我有一个简单的包,用于在程序运行期间记录统计信息,我发现 go run -race 说其中存在竞争条件。查看该程序,我不确定每次读写都受互斥锁保护时如何出现竞争条件。谁能解释一下?

package counters

import "sync"

type single struct {
mu sync.Mutex
values map[string]int64
}

// Global counters object
var counters = single{
values: make(map[string]int64),
}

// Get the value of the given counter
func Get(key string) int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
return counters.values[key]
}

// Incr the value of the given counter name
func Incr(key string) int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
counters.values[key]++ // Race condition
return counters.values[key]
}

// All the counters
func All() map[string]int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
return counters.values // running during write above
}

我这样使用包:

counters.Incr("foo")
counters.Get("foo")

最佳答案

A Minimal Complete Verifiable Example 在这里很有用,但我认为你的问题在 All() 中:

// All the counters
func All() map[string]int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
return counters.values // running during write above
}

这会返回一个 map,它不会复制它,因此可以在互斥锁的保护之外访问它。

关于debugging - Golang 在 map[string]int 上与 sync.Mutex 竞赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153912/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com