首页 > 解决方案 > Golang atomic.StorePointer(...) 行为怪异

问题描述

尝试使用 atomic 包并得到一个很奇怪的行为,可能不理解规范......

游乐场: https: //play.golang.org/p/oPeqwETBpuZ

代码:

func main() {
    x := 1
    y := 2
    xp := &x
    yp := &y
    fmt.Println("xp before: ", xp)
    fmt.Println("yp before: ", yp)
    xpu := (unsafe.Pointer)(xp)
    ypu := (unsafe.Pointer)(yp)
    atomic.StorePointer(&xpu, ypu)
    fmt.Println("xp  after: ", xp)
    fmt.Println("yp  after: ", yp)
}

输出:

xp before:  0xc000100010
yp before:  0xc000100018
xp  after:  0xc000100010
yp  after:  0xc000100018

预期的:

xp before:  0xc000100010
yp before:  0xc000100018
xp  after:  0xc000100018
yp  after:  0xc000100018

我做错了什么?

标签: goatomic

解决方案


正确的方式: https: //play.golang.org/p/__P_5E4di79

事实上,函数需要 **int 强制转换为 *unsafe.Pointer


推荐阅读