Go: How Does Go Recycle Goroutines?
ℹ️ This article is based on Go 1.13.
Goroutines are easy to create, have a small stack, and a fast context switch. For those reasons, developers love them and use them a lot. However, a program that spawns many short living goroutines will spend quite some time creating and destroying them.
Cycle of life
Let’s start with a simple example that will show how goroutines are reused. I will take the prime number calculation from the Go documentation:
Hundreds of goroutines will be used to filter the numbers forcing Go to manage the creation and the destruction of those goroutines. Actually, Go maintains a list of free goroutines per P
:
Keeping this list local per P
brings the advantage not to use any lock to push or get a free goroutine. Then, when a goroutine exits from its current work, it will be pushed to this free list: