This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("sync/atomic" "unsafe") type a struct {x unsafe. Pointery Uint64}func Main () {p: = new (a) atomic. AddUint64 (&P.Y, 1)}
To run the change program on a 32-bit computer, an error occurs:
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 |
The specific reasons for the information are as follows:
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's 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. |
The effect is:
The caller of a 64-bit atomic operation must ensure that the address of the pointer is aligned to a 8-byte boundary |
There are two ways to do this:
1, modify the UInt64 field at the struct's location to ensure that the field address appears at the 8-byte boundary;
2, modify using Sync. Rwmutex to implement mutual exclusion, as follows
Mutex. Lock () UInt64 + = 1mutex. Unlock ()
Suggest a solution to the problem and solve it thoroughly