Why does the code snippet below print out 0
? However, i
is correctly updated to 1
without the for
loop.
package main
import (
"fmt"
"time"
)
func main() {
var i uint64
go func() {
for {
i++
}
}()
time.Sleep(time.Second)
fmt.Println(i)
}
Solution 1
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var i uint64
ch := make(chan bool)
go func() {
for {
select {
case <-ch:
return
default:
i++
}
}
}()
time.Sleep(time.Second)
ch <- true
fmt.Println(i)
}
Solution 2
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var i uint64
var mx sync.Mutex
go func() {
for {
mx.Lock()
i++
mx.Unlock()
}
}()
time.Sleep(time.Second)
mx.Lock()
fmt.Println(i)
mx.Unlock()
}
Solution 3
package main
import (
"fmt"
"runtime"
"sync/atomic"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var i uint64
go func() {
for {
atomic.AddUint64(&i, 1)
runtime.Gosched()
}
}()
time.Sleep(time.Second)
fmt.Println(atomic.LoadUint64(&i))
}