I’m trying to understand concurrency in Go. In particular, I wrote this thread-unsafe program:
package main
import "fmt"
var x = 1
func inc_x() { //test
for {
x += 1
}
}
func main() {
go inc_x()
for {
fmt.Println(x)
}
}
I recognize that I should be using channels to prevent race conditions with x, but that’s not the point here. The program prints 1 and then seems to loop forever (without printing anything more). I would expect it to print an infinite list of numbers, possibly skipping some and repeating others due to the race condition (or worse — printing the number while it is being updated in inc_x).
My question is: Why does the program only print one line?
Just to be clear: I’m not using channels on purpose for this toy example.
There are a few things to keep in mind about Go’s goroutines:
GOMAXPROCSand defaults to 1 currently I think. This may change in the futureruntime.Gosched()explicitly yields control back to the threadThe behavior you are seeing is because the main function never yields back to the thread and is instead involved in a busy loop and since there is only one thread the main loop has no place to run.