I would like to understand how golang is using more than 1 CPU and multiple threads for a program without adding goroutines?
Would it use by default all the cores defined by GOMAXPROCS?
time go run main.go
go run main.go 281.55s user 32.68s system 166% cpu 3:08.59 total
Here is what the activity monitor shows
Answers
In Go, by default, the runtime automatically manages goroutines and how they are scheduled across multiple CPU cores. Even without explicitly using goroutines in your code, if your program is CPU-bound and performs parallelizable tasks, the Go runtime will utilize multiple CPU cores to execute your code efficiently.
The GOMAXPROCS
environment variable or the runtime.GOMAXPROCS()
function can be used to control the maximum number of operating system threads that can simultaneously execute Go code. If GOMAXPROCS
is not set explicitly, Go runtime will default to using the number of logical CPUs available on your system.
When you run a Go program, especially if it's CPU-intensive, the Go runtime will distribute the workload across multiple threads and CPU cores to take advantage of parallelism and improve performance. This is why you see your Go program utilizing multiple CPU cores when monitoring system activity.
In your case, when you run your Go program using go run main.go
, you observe that the CPU usage exceeds 100% because your program is utilizing more than one CPU core, which is indicative of parallel execution across multiple cores. This behavior is typical for CPU-bound tasks in Go programs.