Golang atomic.StorePointer(…)表现很怪异

问题描述 投票:-1回答:1

尝试使用原子包,并且出现了很奇怪的行为,可能是不了解规范...

游乐场: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

我做错了什么?

go atomic
1个回答
1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.