问题描述
>在这里,您需要在goroutine中进行某种同步以保证 done 在 main 中循环的迭代之前发生。 / p>
(Go中不存在)应该被替换为,例如,您阻止的频道(等待沟通)
pre $ 为{
}
基于频道( c:= make(chan bool)$在 main 中创建,并在goroutine中关闭( close(c))。
提供了其他方法来等待gorountine在退出main之前结束。
参见Golang示例:
var w sync.WaitGroup
w.Add(1)
go func(){
//做某事
w.Done()
}
w.Wait()
var x int done := false go func() { x = f(...); done = true } while done == false { }
This is a Go code piece. My fiend told me this is UB code. Why?
As explained in "Why does this program terminate on my system but not on playground?"
(in your case, there is no guarantee that the value written to done in the goroutine will ever be observed by the main program)
Here, You need to do some kind of synchronization in the goroutine in order to guarantee that done=true happens before one of the iterations of the for loop in main.
The "while" (non-existent in Go) should be replaced by, for instance, a channel you block on (waiting for a communication)
for { <-c // 2 }
Based on a channel (c := make(chan bool)) created in main, and closed (close(c)) in the goroutine.
The sync package provides other means to wait for a gorountine to end before exiting main.
See for instance Golang Example Wait until all the background goroutine finish:
var w sync.WaitGroup w.Add(1) go func() { // do something w.Done() } w.Wait()
这篇关于为什么此代码未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!