Understanding goroutines
concurrency, go, race-condition
Solution
There are a few things to keep in mind about Go's goroutines:
- They are not threads in the sense of Java's or C++ threads
- goroutines are more like greenlets
- The go runtime multiplexes the goroutines across the system threads
- the number of system threads is controlled by an environment variable `GOMAXPROCS` and defaults to 1 currently I think. This may change in the future
- The way goroutines yield back to their current thread is controlled by several different constructs
- the select statement can yield control back to the thread
- sending on a channel can yield control back to the thread
- doing IO operations can yield control back to the thread
- `runtime.Gosched()` explicitly yields control back to the thread
The 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.
Problem
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.