doulin2947 2017-12-11 10:34
浏览 157
已采纳

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

I want to write some code like this:

var myValue interface{}

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

func StoreMyValue(newValue interface{}) {
    atomic.Store(myValue, newValue)
}

It seems like that i can use LoadUintptr(addr *uintptr) (val uintptr) and StoreUintptr(addr *uintptr, val uintptr) in atomic package to achive this,but i do not know how to convert between uintptr,unsafe.Pointer and interface{}.

If i do it like this:

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)
}

the V will always be 1

  • 写回答

3条回答 默认 最新

  • dongtan8979 2017-12-11 13:11
    关注

    If I'm not mistaken you want atomic Value. You can store and fetch values atomically with it (signatures are interface{} but you should put same type into it). It does some unsafe pointer stuff under the hood like what you wanted to do.

    Sample from docs:

    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
                    }
            }()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题