2 回答

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

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)
}
- 2 回答
- 0 關注
- 134 瀏覽
添加回答
舉報