package main import ( "sync/atomic" "unsafe" ) type a struct { x unsafe.Pointer y uint64 } func main() { p := new(a) atomic.AddUint64(&p.y, 1) }
在32位計算機上運行改程序,會出現錯誤:ui
panic: runtime error: invalid memory address or nil pointer dereferencegoogle [signal 0xc0000005 code=0x0 addr=0x0 pc=0x4198bc]atom goroutine 1 [running]:spa runtime.panic(0x41c740, 0x445e4f)指針 C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/runtime/panic.c:266 +0xa6code sync/atomic.AddUint64(0x114434ac, 0x1, 0x0, 0x4107e3, 0x397fcc)it C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/sync/atomic/asm_386.s:118 +0xcio main.main()asm E:/Work/GoLang/src/demo/goBug/atomic/main.go:17 +0x4dtable |
查了資料具體緣由以下:
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來完全解決問題