Sobes.tech
Junior — Middle

How is the distribution of goroutines across execution threads implemented?

sobes.tech AI

Answer from AI

In Go, the scheduling of goroutines onto OS threads is handled by the runtime's scheduler. A goroutine is a lightweight coroutine that does not directly correspond to a single OS thread.

The Go scheduler uses an M:N model, where M is the number of OS threads and N is the number of goroutines. It dynamically maps goroutines to threads to efficiently utilize available system resources.

Main components:

  • G (goroutine) — the goroutine itself.
  • M (machine) — an OS thread.
  • P (processor) — a logical processor that manages goroutine execution.

Process:

  1. A goroutine is assigned a P.
  2. The P is associated with an M (OS thread).
  3. The M executes the goroutine.

If a goroutine blocks (for example, on a system call), the scheduler can switch execution to another goroutine on a different thread to avoid idle time.

Thus, the distribution of goroutines across threads happens automatically and transparently to the developer, ensuring high concurrency and scalability.

Example of creating a goroutine:

 go func() {
    fmt.Println("Hello from goroutine")
}()

Here, the scheduler will decide on which OS thread to run this goroutine.

How is the distribution of goroutines across… - sobes.tech