The 'runtime' Package

This lesson will provide some useful information on the runtime Package.

We'll cover the following

Hopefully, you are fully aware by now that concurrency is not the same as parallelism. Now, Go provides us with building blocks of concurrency such as goroutines and channels which allow us to solve the problem concurrently. We can solve the problem through parallelism by running concurrent operations on additional CPUs. This is only possible if the problem to be solved is solvable by adding more CPUs. Thus, we can speed up solving problems by providing the necessary hardware. However, it is not necessary that our program will always speed up by adding CPUs. For example, by adding more CPUs, you are increasing the cost of communication/synchronization between operations as communication between OS threads require a significant cost. Hence, you have to optimize your design and resources.

Let’s see how can we control the number of CPUs for our programs to optimize our solution:

runtime package

The “runtime” package provides us with functions that allow us to control goroutines by interacting with Go’s runtime.

GOMAXPROCS

Here is an example of a useful function:

GOMAXPROCS() : func GOMAXPROCS(n int) int

GOMAXPROCS allows us to set the maximum number of CPUs that can be executed simultaneously. Calling the function will set the number of CPUs to be n but will return the previous value set for the number of the CPUs. The default value for this function is the number of CPUs available. If we input n less than 1, the function will return the previous setting. Have a look below:

Get hands-on with 1400+ tech skills courses.