Goroutine
Goroutines are not threads
-
The Go runtime efficiently manages a pool of OS threads to execute many goroutines. It intelligently schedules goroutines onto these threads, switching between them as needed. This multiplexing allows for highly concurrent applications without the overhead of creating and managing a large number of OS threads.
-
The Go runtime does not assign one goroutine per thread. Instead, it uses a more efficient model called M:N scheduling. This means that multiple goroutines (M) can be multiplexed onto a smaller number of OS threads (N).
How does go runtime put two goroutines on to the same thread?
- The Go runtime uses time-slicing technique to efficiently manage the execution of multiple goroutines on a single thread. This involves dividing the available processor time into small time slices.
- Here's how it works:
- Time Slice Allocation: The runtime allocates a small time slice to a goroutine.
- Goroutine Execution: The goroutine executes its code for the duration of the time slice.
- Context Switching: When the time slice ends, the runtime switches to another goroutine, even if the previous one hasn't finished its work.
- Rescheduling: The interrupted goroutine is placed back in the run queue to be scheduled again later.
- Key Points:
- Concurrent Execution: While two goroutines might be assigned to the same thread, they are not executed simultaneously. Instead, they are executed concurrently, meaning they share the same CPU time in an interleaved manner.
- Illusion of Concurrency: The time-slicing mechanism gives the illusion of concurrent execution, as the goroutines appear to be running simultaneously.
- Efficient Resource Utilization: By multiplexing multiple goroutines onto fewer threads, the Go runtime can efficiently utilize system resources and improve performance.
- It's important to note that the Go runtime's scheduler is highly optimized and can dynamically adjust the scheduling strategy based on various factors, such as the number of available CPUs, the load on the system, and the priority of the goroutines.