Goroutines

Threads have a minimum size in memory; usually, it is in the order of MBs (2 MB for Linux). The minimum size sets some limitations on the application creation of a new thread—if each thread is at least some MBs, 1,000 threads will occupy at least a few GBs of memory. The way that Go tackles these issues is through the use of a construct similar to threads, but this is handled by the language runtime instead of the OS. The size of a goroutine in memory is three orders of magnitude (2 KB per goroutine), meaning that the minimum memory usage of 1,000 goroutines is comparable to the memory usage of a single thread.

This is obtained by defining what data the goroutines are retaining internally, using a data structure called g that describes the goroutine information, such as stack and status. This is an unexported data type in the runtime package and it can be found in the Go source code. Go keeps a track of OSes using another data structure from the same package called m. The logical processors that are acquired in order to execute a goroutine are stored in p structures. This can be verified in the Go runtime package documentation:

These three entities interact as follows—for each goroutine, a new g gets created, g is queued into p, and each p tries to acquire m to execute the code from g. There are some operations that will block the execution, such as these:

  • Built-in synchronization (channels and the sync package)
  • System calls that are blocking, such as file operations
  • Network operations

When these kinds of operations happen, the runtime detaches p from m and uses (or creates, if it does not already exist) another dedicated m for the blocking operation. The thread becomes idle after executing such operations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.76.72