I'm realizing my very first Golang
application and I'm having some issues on using MAX CPU & Cores
when using GoRoutines
and I don't really know why.
When using a tool such as htop
, CPU
isn't used at its max power and only 1..4 threads
are active at time. Also, all cores
are active but they are around 25%-40%
utilization.
I used:
func MaxParallelism() int {
maxProcs := runtime.GOMAXPROCS(0)
numCPU := runtime.NumCPU()
if maxProcs < numCPU {
return maxProcs
}
return numCPU
}
In order to get the number of goroutines
to be instantiated.
Here's How I set up the application:
//Common Channel for the goroutines
tasks := make(chan *exec.Cmd, 64)
//Spawning Max Cores Number goroutines (8)
var wg sync.WaitGroup
cores := MaxParallelism()
for i := 0; i < cores; i++ {
wg.Add(1)
go func(num int, w *sync.WaitGroup) {
defer w.Done()
var (
out []byte
err error
)
for cmd := range tasks {
out, err = cmd.Output()
if err != nil {
fmt.Printf("Can't get stdout:", err)
}
. . .
}
}(i, &wg)
}
//Generate Tasks
for i := 0; i < 100000; i++ {
tasks <- exec.Command(cmd1, args...)
tasks <- exec.Command(cmd2, args...)
}
close(tasks)
// wait for the workers to finish
wg.Wait()
I share two screenshots of htop
while executing the application
I don't know If it May help but I'm launching it through Intellij Idea
.
How do I use Max CPU properly and Cores?
Thanks in advance.