如何在golang中原子存储和加载接口?

Hon*_*hen 6 atomic go

我想写一些这样的代码:

var myValue interface{}

func GetMyValue() interface{} {
    return atomic.Load(myValue)
}

func StoreMyValue(newValue interface{}) {
    atomic.Store(myValue, newValue)
}
Run Code Online (Sandbox Code Playgroud)

似乎我可以在原子包中使用LoadUintptr(addr *uintptr) (val uintptr)StoreUintptr(addr *uintptr, val uintptr)来实现这一点,但我不知道如何在uintptrunsafe.Pointerinterface之间进行转换{}

如果我这样做:

var V interface{}

func F(v interface{}) {
    p := unsafe.Pointer(&V)
    atomic.StorePointer(&p, unsafe.Pointer(&v))
}

func main() {
    V = 1
    F(2)
    fmt.Println(V)
}
Run Code Online (Sandbox Code Playgroud)

V将始终是1

Arm*_*ani 10

如果我没记错的话,你想要atomic Value。您可以使用它以原子方式存储和获取值(签名是,interface{} 但您应该将相同的类型放入其中)。它在引擎盖下做了一些不安全的指针事情,就像你想做的那样。

来自文档的示例:

var config Value // holds current server configuration
// Create initial config value and store into config.
config.Store(loadConfig())
go func() {
        // Reload config every 10 seconds
        // and update config value with the new version.
        for {
                time.Sleep(10 * time.Second)
                config.Store(loadConfig())
        }
}()
// Create worker goroutines that handle incoming requests
// using the latest config value.
for i := 0; i < 10; i++ {
        go func() {
                for r := range requests() {
                        c := config.Load()
                        // Handle request r using config c.
                        _, _ = r, c
                }
        }()
}
Run Code Online (Sandbox Code Playgroud)