Middle+
// What will be output? ```go package main import ( "fmt" "runtime" ) func main() { runtime.GOMAXPROCS(1) done := false go func() { done = true }() for !done { } fmt.Println("finished") } ```
sobes.tech AI
Answer from AI
This code may encounter an infinite loop situation. The variable done is modified in a goroutine, but there is no synchronization mechanism or use of atomic operations in the main goroutine to guarantee visibility of the changes.
Due to compiler optimizations and CPU caching, the main loop for !done {} may never see the update done = true from another goroutine, causing the program to hang in this loop.
If you remove runtime.GOMAXPROCS(1), allowing the scheduler to use multiple OS threads, the likelihood of seeing the update increases but is not guaranteed without synchronization.
The correct way is to use channels or synchronization from the sync/atomic package.
Example with a channel:
package main
import "fmt"
func main() {
done := make(chan struct{})
go func() {
done <- struct{}{}
}()
<-done
fmt.Println("finished")
}