Parallelism in Go
So far, the discussion in this chapter has focused on synchronizing concurrent programs. As was mentioned earlier in the chapter, the Go runtime scheduler automatically multiplexes and schedules goroutines across available OS-managed threads. This means concurrent programs that can be parallelized have the ability to take advantage of the underlying processor cores with little to no configuration. For instance, the following code cleanly segregates its work unit (to calculate sums of multiples of 3 and 5) to be calculated by launching workers
number of goroutines:
const MAX = 1000 const workers = 2 func main() { values := make(chan int) result := make(chan int, workers) var wg sync.WaitGroup go func() { // gen multiple of 3 & 5 values for i := 1; i < MAX; i++ { if (i%3) == 0 || (i%5) == 0 { values <- i // push downstream ...