Reduce Scheduling Contention

Powerful Command-Line Applications in Go — by Ricardo Gerardi (56 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Improving the colStats Tool to Process Files Concurrently | TOC | Exercises 👉

Goroutines are relatively cheap, and in some cases it makes sense to create many of them. For example, if the goroutines wait a long time on IO or network response, then the scheduler can execute other goroutines while these are waiting, increasing the efficiency of the program. In our case, the goroutines are mostly CPU-bound, so creating many of them doesn’t improve the efficiency. Instead, creating too many causes scheduling contention. Let’s address this issue by modifying our program to use worker queues. Instead of creating one goroutine per file, you’ll create one goroutine per available CPU. These will be our workers. Another goroutine sends the jobs to be executed by the workers. When no more jobs exist, the workers are done and the program finishes.

Start by adding another package to the import list. The package runtime contains several functions that deal with the Go runtime. You’ll use this package to determine the number of available CPUs:

performance/colStats.v3/main.go

​ ​import​ (
​ ​"flag"​
​ ​"fmt"​
​ ​"io"​
​ ​"os"​
​ ​"runtime"​
​ ​"sync"​
​ )

Next, edit the function run. Add another channel called filesCh of type chan string. This is the queue; you’ll add files to be processed to this channel, and the…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.