Does a goroutine pool make sense like thread pools in other languages?

Issue

I build a simple goroutine worker pool with a few chan for a stream of events and it works totally fine. Due to the nature of goroutines I started to ask myself what I gain by doing that other then limiting the concurrent workers. The gorutines them self don’t have any state they reuse per execution so that there would be value in keeping them around.

So the question is, does it even make sense to start goroutines and reuse them or just always create a fresh one and just limit the number possible to create/run at the same time?

Solution

Since a goroutine is an executing function, it can be thought of as comprising the set of the followng resources:

  • The code it executes;
  • The state the Go runtime scheduler maintains for that goroutine;
  • The state which is private to the goroutine.

The latter is values a goroutine has allocated locally
(on its stack) and on the heap.

The code is shared;
the state in the scheduler has reasonably negligible cost
but the state a goroutine keeps may be costly to re-create.

The latter point may be used as a justification to keep goroutines
around in a pool. But on the other hand, most of the time it’s simpler
to pool the resources group of goroutines carrying out similar tasks
re-use — instead of the goroutines themselves.

Answered By – kostix

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.