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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探