gpt4 book ai didi

go - 我们只能使用没有volatile的RWMutex?

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:14 24 4
gpt4 key购买 nike

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 中,volatile 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)
}

最佳答案

这里有一些其他选项。

忙等等。这个程序在当前版本的 Go 中完成,但规范不保证它。 Run it on the playground .

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

channel 。 Run it on the playground .

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

WaitGroup . Run it on the playground .

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

关于go - 我们只能使用没有volatile的RWMutex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58021609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com