增量器失灵
时间:2024-03-15
浏览:115
作者:佚名
**增量器失灵:原子增量器在值接收器上使用不当** 在 Go 语言中,使用原子增量器时,必须将接收器类型声明为指针(*),以修改结构的实际值。使用值接收器会创建该结构的副本,对副本进行修改,但不会反映在原始结构中。这会导致原子增量器无法正确递增计数,从而导致不准确的结果。
问题内容
我有一些代码应该增加计数。
这是包含计数变量的结构:
type pipelinedata struct {
nodedata map[string]map[string]int
lastburstresults map[string]map[string]string
burstready map[string]bool
lastexecutiontime map[string]time.time
currentnodesize uint64
}
正如您所看到的,有一个名为 currentnodesize 的成员。该变量旨在每次调用函数 addnodedata 时递增。您可以看到函数 addnodedata 调用函数 addcount,然后该函数使用原子增量器。
func (p pipelinedata) addnodedata(key string) {
nodeslot := clusterscenario.getnodeslotbyhashslot(key)
i:=p.nodedata[nodeslot][key]
i++
p.nodedata[nodeslot][key]=i
p.addcount()
fmt.println("adding node count ",p.currentnodesize)
}
func (p pipelinedata) addcount(){
atomic.adduint64(&p.currentnodesize, 1)
}
不幸的是,当我运行这个时:
p.addnodedata("{pipelinetest}.key");
p.addnodedata("{pipelinetest}.key");
p.addnodedata("{pipelinetest}.key");
p.addnodedata("{pipelinetest}.key");
p.addnodedata("{pipelinetest}.key");
p.addnodedata("{pipelinetest}.key");
dump(p.currentnodesize)
输出为 0。
这是 pipelinedata 结构的初始化:
p = &PipelineData{
nodeData:make(map[string]map[string]int,0),
lastBurstResults:make(map[string]map[string]string,0),
burstReady:make(map[string]bool,0),
lastExecutionTime:make(map[string]time.Time,0),
currentNodeSize:0,
}
for i,_ := range clusterScenario.masterNodes{
p.nodeData[i]=make(map[string]int,0)
}
我了解社区要求我进行研究。我不知道此时该做什么。任何帮助将不胜感激。
我还尝试了使用变量的通用增量器,并产生了相同的结果,这就是我尝试原子增量器的原因
解决方案
addcount 采用值接收器,而不是指针,因此它对结构的副本进行操作,递增副本的字段,然后丢弃该副本。将其更改为采用指针:
func (p *PipelineData) addCount(){
这应该可以解决您的问题。
本篇关于《增量器失灵》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
