- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有一个简单的包,用于在程序运行期间记录统计信息,我发现 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/
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我正在开发一个项目,该项目允许用户作为访客或注册用户加入。 有应用范围user具有当前用户类型的 LiveData 的对象 private val _isGuest = MutableLiveData
我正在创建一个应用程序来帮助我们的团队管理 Twitter 竞赛。到目前为止,我已经成功地与 API 进行交互,并返回了一组我需要的推文。 我正在努力决定处理数据库中推文存储的最佳方式、检查它们的频率
我在处理这段特殊代码时遇到了一些麻烦。它要么存在竞争条件,要么存在 quint8 问题。 quint8 chunk3[CHUNK_SIZE_MULT]; memset(chunk3,0x00, siz
我有一个带有 background.js 的 Chrome 扩展程序,其中收集和存储有关页面的信息, chrome.webRequest.onCompleted.addListener( func
我在我的应用程序中遇到了竞争条件,每当我暂停调试时,所有或除 1 个线程外的所有线程都会卡在 syscall_thread_switch 上。它在模拟器上更频繁地重现,但在 iPad Air 上也是如
我有一个简单的包,用于在程序运行期间记录统计信息,我发现 go run -race 说其中存在竞争条件。查看该程序,我不确定每次读写都受互斥锁保护时如何出现竞争条件。谁能解释一下? package c
我是一名优秀的程序员,十分优秀!