我们只能使用RWMutex而不使用易失性吗?

在https://golang.org/ref/mem#tmp_10中,该程序并不安全,如下所示,无法保证打印最新的消息


type T struct {

    msg string

}


var g *T


func setup() {

    t := new(T)

    t.msg = "hello, world"

    g = t

}


func main() {

    go setup()

    for g == nil {

    }

    print(g.msg)

}

在JAVA中,对于易失性g来说是可以的,我们必须使用rwmutex来保持在golang中打印最新的消息,如下所示?



type T struct {

    msg    string

    rwlock sync.RWMutex

}


var g = &T{}


func setup() {

    g.rwlock.Lock()

    defer g.rwlock.Unlock()

    g.msg = "hello, world"

}


func main() {

    go setup()

    printMsg()

}


func printMsg() {

    g.rwlock.RLock()

    defer g.rwlock.RUnlock()

    print(g.msg)

}


回首忆惘然
浏览 90回答 2
2回答

牧羊人nacy

这里还有一些其他选项。忙着等。该程序在当前版本的 Go 中完成,但规范不保证它。&nbsp;在操场上运行它。package mainimport (&nbsp; &nbsp; "runtime"&nbsp; &nbsp; "sync/atomic"&nbsp; &nbsp; "unsafe")type T struct {&nbsp; &nbsp; msg string}var g unsafe.Pointerfunc setup() {&nbsp; &nbsp; t := new(T)&nbsp; &nbsp; t.msg = "hello, world"&nbsp; &nbsp; atomic.StorePointer(&g, unsafe.Pointer(t))}func main() {&nbsp; &nbsp; go setup()&nbsp; &nbsp; var t *T&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; runtime.Gosched()&nbsp; &nbsp; &nbsp; &nbsp; t = (*T)(atomic.LoadPointer(&g))&nbsp; &nbsp; &nbsp; &nbsp; if t != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; print(t.msg)}渠道。在操场上运行它。func setup(ch chan struct{}) {&nbsp; &nbsp; t := new(T)&nbsp; &nbsp; t.msg = "hello, world"&nbsp; &nbsp; g = t&nbsp; &nbsp; close(ch) // signal that the value is set}func main() {&nbsp; &nbsp; var ch = make(chan struct{})&nbsp; &nbsp; go setup(ch)&nbsp; &nbsp; <-ch // wait for the value to be set.&nbsp; &nbsp; print(g.msg)}等待组。在操场上运行它。var g *Tfunc setup(wg *sync.WaitGroup) {&nbsp; &nbsp; t := new(T)&nbsp; &nbsp; t.msg = "hello, world"&nbsp; &nbsp; g = t&nbsp; &nbsp; wg.Done()}func main() {&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go setup(&wg)&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; print(g.msg)}

千巷猫影

我认为使用渠道会更好。type T struct {&nbsp; &nbsp; msg string&nbsp; &nbsp; doneC chan struct{}}func NewT() *T {&nbsp; &nbsp; return &T{&nbsp; &nbsp; &nbsp; &nbsp; doneC: make(chan struct{}, 1),&nbsp; &nbsp; }}func (t *T) setup() {&nbsp; &nbsp; t.msg = "hello, world"&nbsp; &nbsp; t.doneC <- struct{}{}}func main() {&nbsp; &nbsp; t := NewT()&nbsp; &nbsp; go t.setup()&nbsp; &nbsp; <- t.doneC // or use select to set a timeout&nbsp; &nbsp; fmt.Println(t.msg)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go