Go Runtime
Internal
Go Runtime Scheduler
The Go runtime scheduler manages all goroutines that are created and need processor time. It binds operating system threads to logic processors, which, in turn, execute goroutines. As goroutines are created, they are placed in the scheduler's global run queue. From there, they are added to a logical processor's run queue and executed. Depending on the scheduling algorithm, a running goroutine can be stopped and rescheduled at any time. When a goroutine makes a blocking system call, the scheduler will detach the thread from the processor and create a new thread to service that processor. When a goroutine makes a network I/O call, the goroutine is detached from the logical processor and moved to the runtime network poller. Once the poller indicates a read or write operation is ready, the goroutine is assigned back to a logical processor to handle the operation.
OS Thread
OS threads are referred by the scheduler code as "machines". Also see:
Logical Processor
Go logical processors execute goroutines. Each logical process is individually bound to a single operating system thread.
SetMaxThreads
The Go runtime limits each program to a maximum 10,000 threads by default. This value can be changed by setting SetMaxThreads
in runtime/debug
package.
Goroutine Management
Goroutines do not define their own suspension or reentry points. Go runtime observes the behavior of goroutines and automatically suspends them when they block, and then resumes them when they become unblocked. Go follows a model of concurrency called the fork-join model. At any point in the program, a child branch of execution can be split off. The branch will run concurrently with its parent. At some point in the future, the concurrent branches of execution will join back together, through channels or types in the sync
package, or the child branch will just simply exit. Where the child rejoins the parent is called a join point. A join point can be created by synchronizing the parent and the child branches, with, for example, WaitGroup#Wait()
.
The Go runtime manages goroutines with an M:N scheduler: it maps M logical processors to N O/S threads. Goroutines are scheduled onto logical processors. When there are more goroutines than logical processors available, the scheduler handles the distribution of the goroutines across the available logical processors and ensures that when these goroutines become blocked, other goroutines can be run.
Also see:
Goroutines and Garbage Collection
Goroutines are not garbage collected.
GOMAXPROCS
A function of the runtime
package that controls the number of OS threads that will host so called "work queues". Since Go 1.5 it is automatically set to the number of cores on the host machine.