atomic.LoadInt64 与 atomic.StoreInt64
使用 go run -build
编译运行时下面两者区别
可以参考
https://studygolang.com/articles/29579
优雅上锁,同时保证读写的原子性:直接变量访问指令可能不会引起内存的读取,现在编译器都会做优化,可以把变量优化到寄存器,在代码运气期间对变量的读写直接访问寄存器,而不写入内存;这在同一个执行上下文是没有问题的,而如果需要跨线程访问,则永远看不到变量值的变化。
package main
import (
"fmt"
"time"
)
var x int64 = 0x3333333333333333
func storeFunc() {
for i := 0; ;i++ {
if i % 2 == 0 {
x = 0x1111111111111111
} else {
x = 0x2222222222222222
}
//time.Sleep(10 * time.Millisecond)
}
}
func main() {
go storeFunc()
for {
time.Sleep(10 * time.Millisecond)
fmt.Printf("%x\n", x)
}
}
package main
import (
"fmt"
"sync/atomic"
"time"
)
var x int64 = 0x3333333333333333
func storeFunc() {
for i := 0; ; i++ {
if i%2 == 0 {
atomic.StoreInt64(&x, 0x1111111111111111)
} else {
atomic.StoreInt64(&x, 0x2222222222222222)
}
}
}
func main() {
go storeFunc()
for {
time.Sleep(10 * time.Millisecond)
z := atomic.LoadInt64(&x)
fmt.Printf("%x\n", z)
}
}