http://www.baidu.com/link?url=qb02vICS8NhIztRZ1n7wWHiJ6bDGFeIKQQQfr0w0BShbImeG_EuBkDGEiGzYUF44vQUB6lk_6z11UVP4fcDtonzmlvY0LM6fy-t-Yu6bDIa
@H_
404_14@
赞0
packagemain
import(
"sync/atomic"
"unsafe"
)
typeastruct{
xunsafe.Pointer
yuint64
}
funcmain(){
p:=new(a)
atomic.AddUint64(&p.y,1)
}
@H_
404_14@在32位计算机上运行改程序,会出现
错误:
@H_404_14@panic: runtime error: invalid memory address or nil pointer dereference @H_404_14@[signal 0xc0000005 code=0x0 addr=0x0 pc=0x4198bc] @H_404_14@goroutine 1 [running]: @H_404_14@runtime.panic(0x41c740,0x445e4f) @H_404_14@C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/runtime/panic.c:266 +0xa6 @H_404_14@sync/atomic.AddUint64(0x114434ac,0×1,0×0,0x4107e3,0x397fcc) @H_404_14@C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/sync/atomic/asm_386.s:118 +0xc @H_404_14@main.main() @H_404_14@E:/Work/GoLang/src/demo/goBug/atomic/main.go:17 +0x4d |
@H_
404_14@查了资料具体原因如下:
@H_404_14@https://code.google.com/p/go/issues/detail?id=5278 @H_404_14@On x86-32,the 64-bit functions use instructions unavailable before the @H_404_14@ Pentium MMX. On both ARM and x86-32,it is the caller’s responsibility to @H_404_14@ arrange for 64-bit alignment of 64-bit words accessed atomically. The @H_404_14@ first word in a global variable or in an allocated struct or slice can be @H_404_14@ relied upon to be 64-bit aligned. |
@H_
404_14@其大意是:
@H_404_14@64位原子操作的调用者必须确保指针的地址是对齐到8字节的边界 |
@H_
404_14@的办法有两种:
@H_
404_14@1,
修改uint64字段在struct 的位置确保字段地址出现在8字节的边界;
@H_
404_14@2,
修改使用sync.RWMutex来实现互斥,如下
mutex.Lock()
uint64+=1
mutex.Unlock()
@H_
404_14@建议使用办法2来彻底
解决问题
@H_
404_14@@H_
502_6@ 声明:OSCHINA
博客文章版权属于作者,受法律保护。未经作者同意不得转载。 No tags for this post.