Understanding goroutines

There are a few things to keep in mind about Go’s goroutines:

  1. They are not threads in the sense of Java’s or C++ threads
    • goroutines are more like greenlets
  2. 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
  3. 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.

Leave a Comment