This code prints 0, but if I insert time.Sleep(0) into the updater loop, it prints >1
var Nonce int = 0
func Updater(){
for{
Nonce += 1
}
}
func main(){
go Updater()
time.Sleep(time.Second)
fmt.Printf("%d
",Nonce)
}
This code prints 0, but if I insert time.Sleep(0) into the updater loop, it prints >1
var Nonce int = 0
func Updater(){
for{
Nonce += 1
}
}
func main(){
go Updater()
time.Sleep(time.Second)
fmt.Printf("%d
",Nonce)
}
Your main
function spins up a goroutine to run Updater
and then immediately exits. Without the sleep, Updater
doesn't have time to start and do its thing. This code is racy - it will sometimes work as you expect and sometimes won't. You have to synchronize the Updater
goroutine with main
somehow, using a channel or a wait group for example.
Moreover, you're updating the Nonce
global in one goroutine and reading it in another - this is a data race. You'll need to synchronize access to this var with a mutex.
Here's a more correct variant of your code, though it's still rather non-sensical (why do you need a goroutine to run the busy loop?)
package main
import (
"fmt"
"sync"
)
var Nonce int = 0
func Updater(wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 1000; i++ {
Nonce += 1
}
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go Updater(&wg)
wg.Wait()
fmt.Printf("%d
", Nonce)
}
Here we use a WaitGroup
for the Updater
to signal "I'm done" to the main goroutine, which only then checks the value of Nonce
. This program should print "1000" every time