Is assigning a pointer atomic in Go?

前端 未结 3 1286
梦谈多话
梦谈多话 2020-12-16 11:16

Is assigning a pointer atomic in Go?

Do I need to assign a pointer in a lock? Suppose I just want to assign the pointer to nil, and would like other threads to be abl

3条回答
  •  被撕碎了的回忆
    2020-12-16 11:54

    In addition to Nick's answer, since Go 1.4 there is atomic.Value type. Its Store(interface) and Load() interface methods take care of the unsafe.Pointer conversion.

    Simple example:

    package main
    
    import (
        "sync/atomic"
    )
    
    type stats struct{}
    
    type myType struct {
        stats atomic.Value
    }
    
    func main() {
        var t myType
        
        s := new(stats)
        
        t.stats.Store(s)
        
        s = t.stats.Load().(*stats)
    }
    

    Or a more extended example from the documentation on the Go playground.

提交回复
热议问题