|
|
|
|
|
by alecrn
3409 days ago
|
|
Yeah, this particular instance seems ok to me. This one makes the example feel weirder: func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println(runtime.NumCPU(), runtime.GOMAXPROCS(0))
started := make(chan bool)
go func() {
started <- true
for {
atomic.AddUint64(&a, uint64(1))
}
}()
<-started
for {
fmt.Println(atomic.LoadUint64(&a))
time.Sleep(time.Second)
}
}
Here we explicitly wait until the goroutine is started, so we know it's scheduled by the time our other loop runs. Here on my computer with go1.8 linux/amd64 it still optimizes out the while loop, which makes sense as nothing changed that would convince the optimizer the loop should remain given the compiler's current logic.If you add time.Sleep(time.Millisecond) to the goroutine loop or any other synchronization it works fine. I'm having trouble thinking of a real world example where you'd want an atomic operation going ham in a loop without any sort of time or synchronization. At the very least a channel indicating when the loop is done would cause the loop to compile. |
|