为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
回首忆惘然 2023-07-26 15:36:00
在https://golang.org/ref/mem#tmp_10中,该程序并不安全,如下所示,无法保证打印最新的消息type T struct {    msg string}var g *Tfunc 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)}
查看完整描述

2 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

这里还有一些其他选项。

忙着等。该程序在当前版本的 Go 中完成,但规范不保证它。 在操场上运行它

package main


import (

    "runtime"

    "sync/atomic"

    "unsafe"

)


type T struct {

    msg string

}


var g unsafe.Pointer


func setup() {

    t := new(T)

    t.msg = "hello, world"

    atomic.StorePointer(&g, unsafe.Pointer(t))

}


func main() {

    go setup()

    var t *T

    for {

        runtime.Gosched()


        t = (*T)(atomic.LoadPointer(&g))

        if t != nil {

            break

        }

    }

    print(t.msg)

}

渠道。在操场上运行它

func setup(ch chan struct{}) {

    t := new(T)

    t.msg = "hello, world"

    g = t

    close(ch) // signal that the value is set

}


func main() {

    var ch = make(chan struct{})

    go setup(ch)

    <-ch // wait for the value to be set.

    print(g.msg)

}

等待组在操场上运行它

var g *T


func setup(wg *sync.WaitGroup) {

    t := new(T)

    t.msg = "hello, world"

    g = t

    wg.Done()

}


func main() {

    var wg sync.WaitGroup

    wg.Add(1)

    go setup(&wg)

    wg.Wait()

    print(g.msg)

}


查看完整回答
反对 回复 2023-07-26
?
千巷猫影

TA贡献1829条经验 获得超7个赞

我认为使用渠道会更好。


type T struct {

    msg string

    doneC chan struct{}

}


func NewT() *T {

    return &T{

        doneC: make(chan struct{}, 1),

    }

}


func (t *T) setup() {

    t.msg = "hello, world"

    t.doneC <- struct{}{}

}


func main() {

    t := NewT()

    go t.setup()

    <- t.doneC // or use select to set a timeout

    fmt.Println(t.msg)

}


查看完整回答
反对 回复 2023-07-26
  • 2 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信