Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了golang在32位系统下atomic.AddUint64导致程序崩溃及解决办法大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
packagemain

import(
	"sync/atomic"
	"unsafe"
)

typeastruct{
	xunsafe.Pointer
	yuint64
}

funcmain(){
	p:=new(a)
	atomic.AddUint64(&p.y,1)
}

在32位计算机上运行改程序,会出现错误

panic: runtime error: invalid memory address or nil pointer dereference

[signal 0xc0000005 code=0x0 addr=0x0 pc=0x4198bc]


goroutine 1 [running]:

runtime.panic(0x41c740,0x445e4f)

C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/runtime/panic.c:266 +0xa6

sync/atomic.AddUint64(0x114434ac,0x1,0x0,0x4107e3,0x397fcc)

C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/sync/atomic/asm_386.s:118 +0xc

main.main()

E:/Work/GoLang/src/demo/goBug/atomic/main.go:17 +0x4d

查了资料具体原因如下:

https://code.google.com/p/go/issues/detail?id=5278

On x86-32,the 64-bit functions use instructions unavailable before the

Pentium MMX. On both ARM and x86-32,it is the caller's responsibility to

arrange for 64-bit alignment of 64-bit words accessed atomically. The

first word in a global variable or in an allocated struct or slice can be

relied upon to be 64-bit aligned.

其大意是:

64位原子操作的调用者必须确保指针的地址是对齐到8字节的边界

的办法有两种:

1,修改uint64字段在struct 的位置确保字段地址出现在8字节的边界;

2,修改使用sync.RWMutex来实现互斥,如下

mutex.Lock()
uint64+=1
mutex.Unlock()

建议使用办法2来彻底解决问题

大佬总结

以上是大佬教程为你收集整理的golang在32位系统下atomic.AddUint64导致程序崩溃及解决办法全部内容,希望文章能够帮你解决golang在32位系统下atomic.AddUint64导致程序崩溃及解决办法所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: