Implementing Goroutines
In the current implementation of the runtime, Go does not parallelize code by default. Only a single core or processor is dedicated to a Go-program, regardless of how many goroutines are started in it. Therefore, these goroutines are _running concurrently; they are not running in parallel, which means only one goroutine is running at a time. This will probably change, but until then, in order to let your program execute simultaneously with more cores so that goroutines are really running in parallel; you have to use the variable GOMAXPROCS
.
This tells the run-time how many goroutines can execute in parallel. For example, if you have 8 processors, you can at most run 8 goroutines in parallel.
Using GOMAXPROCS
The developer must set GOMAXPROCS
to more than the default value 1 to allow the run-time support to utilize more than one OS thread. All goroutines share the same thread unless GOMAXPROCS
is set to a value greater than 1. When GOMAXPROCS
is greater than 1, they run on a thread pool with that many threads.
For Go version 1.5 and higher, default value of GOMAXPROCS
is set to NUMCPU
, which is equal to the number of available logical CPUs. This is done for a good reason. Experience shows that it gives the best performance in most cases. This way you don’t have to benchmark different GOMAXPROCS
values anymore to see which value optimizes your application’s execution.
If you do experience performance problems with this default value, there might be cases when setting GOMAXPROCS
above the number of CPUs increases the performance of your app, but they are rare. Benchmark the performance to find out if it helps in your specific case.
If you’re using Go version less than 1.5, you have to set GOMAXPROCS
manually to NUMCPU
, or call runtime.GOMAXPROCS(runtime.NumCPU())
in your code.
Note: To run in parallel means a goroutine must run on a different thread, and each thread must run on a different processor.
Get hands-on with 1200+ tech skills courses.